- java 二分法源代码采用的方法( Arrays.binarySearch() )
```
public static int binarySearch1(int[] nums, int target){
int left = 0;
int right = nums.length -1; // [ left, right ]
while (left <= right){ // left <= right
int mid = (right - left) / 2 + left;
if(nums[mid] > target){ // [ left, mid -1 ] right = mid - 1;
} else if (nums[mid] < target ){ // [ mid + 1, right ]
left = mid +1;
} else {
return mid;
}
return -1;
} - leetcode见到的二分法
public class Solution {
/**
* @param A an integer array sorted in ascending order
* @param target an integer
* @return an integer
*/
public int findPosition(int[] nums, int target) {
if (nums == null || nums.length == 0) {
return -1;
}
int start = 0, end = nums.length - 1;
while (start + 1 < end) {//这里最关键:保证进入while循环的必须是至少有三个数。
int mid = start + (end - start) / 2;
if (nums[mid] == target) {
return mid;
} else if (nums[mid] < target) { //这里保证的是返回第一个相同值。
start = mid;
} else {
end = mid;
}
}
return -1;
}
}