二分查找
二分可以分为查找左边界&查找右边界
对应模板为:
- 左边界
//search左边界
int searchLeft (int l, int r) {
while (l < r) {
int mid = l + r >> 1;
if (check(mid))
r = mid;
else
l = mid + 1;
}
return l;
}
- 右边界
int searchRight (int l, int r) {
while (l < r) {
int mid = l + r + 1 >> 1;
if (check(mid))
l = mid;
else
r = mid - 1;
}
return l;
}
leetcode 704
题目:
Given an array of integers
nums
which is sorted in ascending order, and an integertarget
, write a function to searchtarget
innums
. Iftarget
exists, then return its index. Otherwise, return-1
.
You must write an algorithm withO(log n)
runtime complexity.
找升序数组中的某个元素
class Solution {
public int search(int[] nums, int target) {
int l = 0, r = nums.length - 1;
while (l < r) {
int mid = l + r >> 1;
if (nums[mid] >= target)
r = mid;
else
l = mid + 1;
}
if (nums[l] != target)
return -1;
else
return l;
}
}
双指针
leetcode27 移除元素
题目:
Given an integer array
nums
and an integerval
, remove all occurrences ofval
innums
in-place. The order of the elements may be changed. Then return the number of elements innums
which are not equal toval
.Consider the number of elements in
nums
which are not equal toval
bek
, to get accepted, you need to do the following things:
- Change the array
nums
such that the firstk
elements ofnums
contain the elements which are not equal toval
. The remaining elements ofnums
are not important as well as the size ofnums
.- Return
k
.
思路:
-
two pointers
两个指针p, q;只需要遍历一遍就可以;
note: 题目最后要返回的是修改后的数组长度,而非Index
assert k == expectedNums.length;
通过&引用来读取新的array -
双向双指针
思路有点类似快排
找到右边!=val
的和左边==val
的进行交换
这样移动次数最少
要注意边界情况
感觉有了思路后,代码实现很简单
思路1:快慢pointer
class Solution {
public int removeElement(int[] nums, int val) {
int p = 0, q = 0;
for (p = 0; p < nums.length; ++p) {
if (nums[p] != val) {
nums[q++] = nums[p];
}
}
return q;
}
}
思路2:双向指针
class Solution {
public int removeElement(int[] nums, int val) {
int p = 0, q = nums.length - 1;
//move q to the place where the 1st value from the right is not val
while (q >= 0 && nums[q] == val)
--q;
while (p <= q) {
if (nums[p] == val) { //replace the value in p with nums[q]
nums[p] = nums[q--];
}
++p;
while (q >= 0 && nums[q] == val)
--q;
}
return p;
}
}
ps: 要尝试给代码写注释