题目链接:704.二分查找
感受:题目很简单,就是在边界条件上要注意循环不变量,假如target是在[low,high]里,那么条件就要写成low<=high,因为low==high还是具备意义的。如果认为target是在[low,high)上,也可以,条件就要写成low<high,因为此时的low==high就没有意义了。
左闭右闭代码:
class Solution {
public:
int search(vector<int>& nums, int target) {
int low=0;
int high=nums.size()-1;
while(low<=high){
int mid = low + (high-low)/2;
if(nums[mid]<target){
low=mid+1;
}
else if(nums[mid]>target){
high=mid-1;
}
else{
return mid;
}
}
return -1;
}
};
题目链接:35.搜索插入位置
和上题一样,就是对于没有的元素要插入进数组。分三种情况,一种是插在头,一种插在尾,一种插中间。三种情况都是把数插在high+1的位置上。
代码:
class Solution {
public:
int searchInsert(vector<int>& nums, int target) {
int low=0;
int high=nums.size()-1;
while(low<=high){
int mid = low + (high-low)/2;
if(nums[mid]>target){
high=mid-1;
}
else if(nums[mid]<target){
low=mid+1;
}
else
return mid;
}
return high+1;
}
};
思路:这次要查找一个范围,左右边界分开查找。
代码:
class Solution {
public:
vector<int> searchRange(vector<int>& nums, int target) {
int leftBorder = getLeftBorder(nums, target);
int rightBorder = getRightBorder(nums, target);
if (leftBorder == -2 || rightBorder == -2) return {-1, -1};
if (rightBorder - leftBorder > 1) return {leftBorder + 1, rightBorder - 1};
return {-1, -1};
}
int getLeftBorder(vector<int>& nums, int target){
int left=0;
int right=nums.size()-1;
int leftboard=-2;
while(left<=right){
int mid=left+(right-left)/2;
if(nums[mid]>=target){
right=mid-1;
leftboard=right;
}
else{
left=mid+1;
}
}
return leftboard;
}
int getRightBorder(vector<int>& nums, int target) {
int left = 0;
int right = nums.size() - 1;
int rightBorder = -2;
while (left <= right) {
int middle = left + ((right - left) / 2);
if (nums[middle] > target) {
right = middle - 1;
} else {
left = middle + 1;
rightBorder = left;
}
}
return rightBorder;
}
};
题目链接:27.移除元素
思路:双指针,直接取满足条件的元素覆盖val的元素
代码:
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];
}
}
return slow;
}
};