三种二分法模板
第一种
要点:详见另一篇文章二分搜索 Binary Search
class Solution{
public int search1(int[] nums, int target) {
if (nums == null || nums.length == 0){
return -1;
}
int left = 0, right = nums.length - 1;
while (left + 1 < right) {
int mid = left + (right - left) / 2;
if (nums[mid] == target) {
right = mid;//要点4
} else if (nums[mid] < target) {
left = mid;
} else if (nums[mid] > target) {
right = mid;
}
}
if (nums[left] == target) {
return left;
}
if (nums[right] == target) {
return right;
}
return -1;
}
}
第二种
要点:
- left <= right 左闭右闭区间
- right为数组的长度-1
class Solution {
public int search2(int[] nums, int target) {
int left = 0, right = nums.length-1;
while(left <= right){
int mid = left + (right - left)/2;
if(nums[mid] > target){
right = mid -1;
}else if (nums[mid] < target){
left = mid + 1;
}else{
return mid;
}
}
return -1;
}
}
第三种
要点:
- left < right 左闭右开区间
- right为数组的长度
class Solution {
public int search3(int[] nums, int target) {
int left = 0, right = nums.length;
while(left < right){
int mid = left+(right -left)/2;
if(target < nums[mid]){
right = mid;
}else if(target > nums[mid]){
left = mid +1;
}else{
return mid;
}
}
return -1;
}
}