LeetCode 704.二分查找
题目链接
704.二分查找
题解
//左闭右闭
class Solution {
public:
int search(vector<int>& nums, int target) {
int left = 0, right = nums.size() - 1;
while (left <= right) {
int middle = left + (right - left) / 2;
if (target > nums[middle]) {
left = middle + 1;
}
else if (target < nums[middle]) {
right = middle - 1;
}
else return middle;
}
return -1;
}
};
//左闭右开
class Solution {
public:
int search(vector<int>& nums, int target) {
int left = 0, right = nums.size();//写法改动点1
while (left < right) {//写法改动点2,当right取到num.size()时left就不应该取到right相等了。
int middle = left + (right - left) / 2;
if (target > nums[middle]) {
left = middle + 1;
}
else if (target < nums[middle]) {
right = middle;//写法改动点3,num[middle]已经被扫描过了,接下来的扫描不应该包括middle
//,right是作为不会被取到的右边界,因此取等于middle
}
else return middle;
}
return -1;
}
};
LeetCode 3.移除元素
题目链接
27.移除元素
题解
//双指针法
class Solution {
public:
int removeElement(vector<int>& nums, int val) {
int slow = 0, fast = 0;
while (fast < nums.size()) {
if (nums[fast] != val) {
nums[slow ++] = nums[fast];
}
fast ++;
}
return slow;
}
};