标签:static else arch 循环 bin while 一个 退出 return
class Solution {
public static void main(String[] args) {
int[] arr = new int[]{0, 1, 2, 2, 2, 3, 4, 5};
//int index = binarySearch(arr, 2);
//int index2 = leftBound(arr, 2);
int index3 = rightBound(arr, 2);
//System.out.println(index + ":" + arr[index]);
//System.out.println(index2 + ":" + arr[index2]);
System.out.println(index3 + ":" + arr[index3]);
}
public static int binarySearch(int[] nums, int target) {
int left = 0;
int right = nums.length - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (nums[mid] == target) {
return mid;
} else if (nums[mid] < target) {
left = mid + 1;
} else if (nums[mid] > target) {
right = mid - 1;
}
}
return -1;
}
/*
* 找左边界和找右边界都有一个退出while循环的情况,即[left==right+1,right]
* 所以:
* 如果找左边界,返回left
* 如果找右边界,返回right
* 当然:
* 返回之前,需要判断left或者right是否越界,即:left>=num.length和right<0
* 并且判断nums[left/right] 是否等于 target
* */
public static int leftBound(int[] nums, int target) {
int left = 0;
int 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 if (nums[mid] > target) {
right = mid - 1;
}
}
if (left >= nums.length || nums[left] != target)
return -1;
return left;
}
public static int rightBound(int[] nums, int target) {
int left = 0;
int right = nums.length - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (nums[mid] == target) {
left = mid + 1;
} else if (nums[mid] < target) {
left = mid + 1;
} else if (nums[mid] > target) {
right = mid - 1;
}
}
if (right < 0 || nums[right] != target)
return -1;
return right;
}
}
标签:static else arch 循环 bin while 一个 退出 return
原文地址:https://www.cnblogs.com/zyk98/p/14594788.html