704. 二分查找
拓展
35.搜索插入位置
34.在排序数组中查找元素的第一个和最后一个位置
问题
Given an array of integers
numswhich is sorted in ascending order, and an integertarget, write a function to searchtargetinnums. Iftargetexists, then return its index. Otherwise, return-1.
You must write an algorithm withO(log n)runtime complexity.
LC链接
leetcode.com/problems/bi…
文章讲解
programmercarl.com/0704.%E4%BA…
使用需满足
- 数组递增或递减
- 无重复元素
重点关注
二分法需注意边界问题, 在代码上主要体现在right的初始值, right值的更新和终止条件.
| right初始值 | right值的更新 | 终止条件 | |
|---|---|---|---|
| 左闭右开 [) | nums.size() | mid | left < right |
| 左闭右闭 [] | nums.size() - 1 | mid - 1 | left <= right |
代码
- 左闭右闭
int search(vector<int>& nums, int target) {
int left = 0;
int right = nums.size() - 1;
while (left <= right) {
int mid = (left + right) / 2;
if (nums[mid] == target) {
return mid;
} else if (nums[mid] < target) {
left = mid + 1;
} else if (nums[mid] > target) {
right = mid - 1;
}
}
return -1;
}
- 左闭右开
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;
}
27. 移除元素
问题
Given an integer array
numsand an integerval, remove all occurrences ofvalinnumsin-place. The order of the elements may be changed. Then return the number of elements innumswhich are not equal toval.
LC链接
leetcode.com/problems/re…
文章讲解
programmercarl.com/0027.%E7%A7…
方法一: Brute Force
需要关注size值的更改方式
int removeElement(vector<int>& nums, int val) {
int size = nums.size();
for (int i = 0; i < size; i++) {
if (nums[i] == val) {
for (int j = i; j < size - 1; j++) {
nums[j] = nums[j+1];
}
i--;
size--;
}
}
return size;
}
方法二: Two pointers
第一个方法比较直观
第二个方法比较简洁快速
int removeElement(vector<int>& nums, int val) {
// for (int i = 0; i < nums.size(); i++) {
// if (nums[i] == val) {
// fast++;
// } else {
// if (fast < nums.size()) {
// nums[slow] = nums[fast];
// slow++;
// fast++;
// }
// }
// }
for (int fast = 0; fast < nums.size(); fast++) {
if (nums[fast] != val) {
nums[slow++] = nums[fast];
}
}
return slow;
}