力扣704,二分查找
本体主要考虑边界问题,区间时左闭右闭还是左闭右开
左闭右闭
class Solution {
public:
int search(vector<int>& nums, int target) {
int left = 0;
int right = nums.size() - 1;
while (left <= right) {
int middle = (left + right) / 2;
if (nums[middle] > target) {
right = middle - 1;
} else if (nums[middle] < target) {
left = middle + 1;
} else {
return middle;
}
}
return -1;
}
};
左闭右开
class Solution {
public:
int search(vector<int>& nums, int target) {
int left = 0;
int right = nums.size();
while (left < right) {
int middle = (left + right) / 2;
if (nums[middle] > target) {
right = middle;
} else if (nums[middle] < target) {
left = middle + 1;
} else {
return middle;
}
}
return -1;
}
};
力扣27,移除元素
和之前的移除字符串中的空格思路一样,双指针法
class Solution {
public:
int removeElement(vector<int>& nums, int val) {
int slow = 0;
for (int fast = 0; fast < nums.size(); fast++) {
if (nums[fast] != val) {
nums[slow] = nums[fast];
slow++;
}
}
return slow;
}
};
力扣977,有序数组的平方
双指针法,需要注意的是往数组中填写结果的方法
class Solution {
public:
vector<int> sortedSquares(vector<int>& nums) {
int left = 0;
int right = nums.size() - 1;
deque<int> res;
while (left <= right) {
if (nums[left] * nums[left] < nums[right] * nums[right]) {
res.push_front(nums[right] * nums[right]);
right--;
} else {
res.push_front(nums[left] * nums[left]);
left ++;
}
}
return vector<int>(res.begin(), res.end());
}
};