方法一:
整个数组是 左闭右闭区间 [ ]
方法二:
整个数组是 左闭右开区间 [ )
整个数组是 左闭右闭区间 [ ]
整个数组是 左闭右开区间 [ )
方法一:
class Solution {
public:
int search(vector<int>& nums, int target) {
int left = 0, right = nums.size()-1;
while(left<=right){
int mid = (left+right)/2;
if(nums[mid] == target){
return mid;
}else if(nums[mid] >target){
right = mid-1;
}else if(nums[mid]< target){
left = mid+1;
}else{
return mid;
}
}return -1;
}
};
方法二:
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;
}
};
方法一:双指针
方法二:
4. 定义left =0 right =nums.size()-1
5. 循环条件 left<=right
6. 左边找到nums[left]==val 的下标
右边找到nums[right] !=val 的下标
交换 nums[left] =nums[right] left++; right–;
结果: return left;
class Solution {
public:
int removeElement(vector<int>& nums, int val) {
int left =0;
int right = nums.size()-1;
while(left<=right){
while(left<=right && nums[left] != val){
left++;
}
while(left<=right && nums[right] == val){
right--;
}
if(left<=right){
nums[left] = nums[right];
left++;
right--;
}
}
return left;
}
};
slow指:更新后 新数组下标
fast 指:寻找新数组的元素
class Solution {
public:
int removeElement(vector<int>& nums, int val) {
int slow =0;
int fast =0;
for(fast = 0; fast <nums.size(); fast++){
if(nums[fast] != val){
nums[slow] = nums[fast];
slow++;
}
}
return slow;
}
};