这是几道Binary search的题,
要注意它的退出条件。
l < r 还是 l <= r 还是 l + 1 < r
l <= r就用l <= r,否则 l < r, 实在不行就 l + 1 < r
- First Bad Version
因为最后只剩一个bad version, 所以肯定是它,直接返回就好了。
注意这一题不能用 l <= r 因为如果只有一个数的话会死循环(r = m)。
public int firstBadVersion(int n) {
int l = 1, r = n;
while (l < r) {
int m = l + (r - l) / 2;
if (isBadVersion(m)) r = m;
else l = m + 1;
}
return l;
}
- Search in Rotated Sorted Array
这题就是在rotated sorted array里面找target。
关键点就是在于找左右两边谁是递增区间。
对于递增区间我们才可以判断我们的target在不在里面。
注意这一题可以用 l <= r 因为如果只有一个数的话也不会死循环(r = m - 1; l = m + 1)。
public int search(int[] nums, int target) {
int l = 0, r = nums.length - 1;
while (l <= r) {
int m = l + (r - l) / 2;
if (nums[m] == target) return m;
if (nums[m] < nums[r]) {
if (target > nums[m] && target <= nums[r]) {
l = m + 1;
} else r = m - 1;
} else {
if (target >= nums[l] && target < nums[m]) {
r = m - 1;
} else {
l = m + 1;
}
}
}
return -1;
}
- Search in Rotated Sorted Array II
public boolean search(int[] nums, int target) {
int l = 0, r = nums.length - 1;
while (l <= r ) {
int m = l + ( r - l) / 2;
if (nums[m] == target) return true;
if (nums[r] > nums[m]) {
if (target > nums[m] && target <= nums[r]) {
l = m + 1;
} else {
r = m - 1;
}
} else if (nums[m] > nums[l]) {
if (target >= nums[l] && target < nums[m]) {
r = m - 1;
} else {
l = m + 1;
}
} else {
if (nums[r] == target) return true;
r--;
}
}
return false;
}
- Find Peak Element
public int findPeakElement(int[] nums) {
int l = 0, r = nums.length - 1;
while (l < r ) {
int m = l + (r - l) / 2;
if (nums[m] < nums[m + 1]) {
l = m + 1;
} else {
r = m;
}
}
return l;
}
- Sqrt(x)
public int mySqrt(int x) {
if (x == 0) return 0;
int l = 1, r = x / 2;
while (l < r) {
int m = r - (r - l) / 2;
long m2 = (long) m * (long) m;
if (m2 == (long) x) return m;
if (m2 < (long) x) l = m;
else r = m - 1;
}
return l;
}
网友评论