1、二分查找
int binarySearch(int[] nums, int target) {
int left = 0, right = ...;
while(...) {
int mid = left + (right - left) / 2;//计算 mid 时需要防止溢出
if (nums[mid] == target) {
...
} else if (nums[mid] < target) {
left = ...
} else if (nums[mid] > target) {
right = ...
}
}
return ...;
}
for example
实现平方根,二分查找0-x
class Solution {
public int mySqrt(int x) {
int low = 0 , high = x , ans = -1;
while(low<=high){
int mid = low + (high-low)/2;
if((long)mid*mid<=x){
ans = mid;
low = mid+1;
}
else{
high = mid-1;
}
}
return ans;
}
}