//保持区间左闭右开不变原则
class Solution {
public:
int search(vector<int>& nums, int target) {
int left = 0;
int right = nums.size();
while (left < right) {
int mid = (left + right) / 2;
if (nums[mid] < target) {
left = mid + 1;
} else if (nums[mid] > target) {
right = mid;
} else {
return mid;
}
}
return -1;
}
};
//同向双指针
class Solution {
public:
int removeElement(vector<int>& nums, int val) {
int nums_size = nums.size();
int slow_index = 0;
for(int fast_index = 0; fast_index < nums_size; fast_index++){
if(nums[fast_index] != val){
nums[slow_index] = nums[fast_index];
slow_index++;
}
}
return slow_index;
}
};
//反向双指针
class Solution {
public:
int removeElement(vector<int>& nums, int val) {
int nums_size = nums.size();
int left_index = 0, right_index = nums_size - 1;
while(left_index <= right_index){ //注意等于号
if(nums[left_index] != val) left_index++;
else {
nums[left_index] = nums[right_index];
right_index--;
}
}
return left_index;
}
};