遇到有序数组、查找这两个关键词要注意能否使用二分法
class Solution {
public:
int search(vector<int>& nums, int target) {
int left = 0, right = nums.size() - 1;
while(right >= left){
int mid = (right + left) / 2;
if(nums[mid] < target) left = mid + 1;
else if(nums[mid] > target) right = mid - 1;
else return mid;
}
return -1;
}
};
对于双指针和快慢指针一定要敏感,特别是在对内存有要求的时候
class Solution {
public:
int removeElement(vector<int>& nums, int val) {
int slow = 0;
for(int num : nums){
if(num != val){
nums[slow++] = num;
}
}
return slow;
}
};