704.二分查找:
1.左闭右闭
int search(vector<int>& nums, int target) {
int right = nums.size() - 1;
int left = 0;
while(left < right){
int middle = left + ((right - left) >> 1);
if(nums.at(middle) == target){
return middle;
}else if(nums[middle] > target){
right = middle - 1;
}else{
left = middle + 1;
}
}
return -1;
}
2.左闭右开
int search(vector<int>& nums, int target) {
int right = nums.size();
int left = 0;
while(left < right){
int middle = left + ((right - left) >> 1);
if(nums.at(middle) == target){
return middle;
}else if(nums[middle] > target){
right = middle;
}else{
left = middle + 1;
}
}
return -1;
}
遇到问题:
如果middle等变量的类型采用auto,跑测试用例nums=[5] target=-5时会报错index越界,后采用int类型。
27.移除元素
int removeElement(vector<int>& nums, int val) {
int length = nums.size();
int count = 0;
for(int i = 0; i < length; i++){
if(nums[i] == val){
continue;
}else{
nums[count++] = nums[i];
}
}
return count;
}
977.有序数组的平方
注意:考虑非单调递减数组前后的平方值是最大的,中间的是最小的。遍历时从两头往中间走,从后往前存计算结果,就能达到上述要求
vector<int> sortedSquares(vector<int>& nums) {
vector<int> result(nums.size());
int left = 0;
int right = nums.size() - 1;
int index = nums.size() - 1;
while(left <= right){
int square_left = nums[left] * nums[left];
int square_right = nums[right] * nums[right];
if(square_left > square_right){
result[index--] = square_left;
left++;
}else{
result[index--] = square_right;
right--;
}
}
return result;
}