LeetCode--704. Binary Search
二分查找的两种写法:
1、循环:
class Solution {
public int search(int[] nums, int target) {
if(nums == null) {
return -1;
}
int lo = 0;
int hi = nums.length - 1;
while(lo <= hi) {
int mid = (lo + hi) / 2;
if(target > nums[mid]) {
lo = mid + 1;
} else if(target < nums[mid]) {
hi = mid - 1;
} else {
return mid;
}
}
return -1;
}
}
2、递归:
class Solution {
public int search(int[] nums, int target) {
return binarySearch(nums, 0, nums.length - 1, target);
}
private int binarySearch(int[] nums, int lo, int hi, int target) {
if(lo > hi) return -1;
int mid = (lo + hi) / 2;
return target > nums[mid] ? binarySearch(nums, mid + 1, hi, target) :
target < nums[mid] ? binarySearch(nums, lo, mid - 1, target) : mid;
}
}