1.有序数组中找到num
package LeetCode;
public class Code1_BSExit {
public static void main(String[] args) {
int [] arr={1,2,2,3,4,5,6,7,8};
int num=5;
boolean b = find(arr, num);
System.out.println(b);
}
public static boolean find(int [] arr,int num){
if (arr== null || arr.length==0){
return false;
}
int L=0;
int R=arr.length-1;
while (L<=R){
int mid = (L+R)/2;
if (arr[mid]==num){
return true;
}else if (arr[mid]>num){
R=mid-1;
}else {
L=mid+1;
}
}
return false;
}
}
2.有序数组中找到>=num的最左位置
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/60ebc468740885bb3f7a5f49e5dff1b8.png)
package LeetCode;
public class Code2_BSNearLeft {
public static void main(String[] args) {
int [] arr={1,2,2,3,4,5,6,7,8};
int num=10;
int i = mostLeftNoMoreNumIndex(arr, num);
System.out.println(i);
}
public static int mostLeftNoMoreNumIndex(int []arr,int num){
if(arr==null || arr.length==0){
return -1;
}
int L=0;
int R=arr.length-1;
int index=-1;
while (L<=R){
int mid =(L+R);
if (arr[mid]>=num){
index=mid;
R=mid-1;
}else {
L=mid+1;
}
}
return index;
}
}
3.有序数组中找到<=num的最右位置
public static int nearestIndex(int[] arr, int value) {
int L = 0;
int R = arr.length - 1;
int index = -1;
while (L <= R) {
int mid = L + ((R - L) >> 1);
if (arr[mid] <= value) {
index = mid;
L = mid + 1;
} else {
R = mid - 1;
}
}
return index;
}
4.局部最小值问题
- 数组无序
- 任意两个相邻位置数不相等
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/1d9f433e74d1d16b95df7deb05af9ac4.png)
public static int oneMinIndex(int [] arr){
if (arr==null || arr.length==0){
return -1;
}
int N=arr.length;
if (N==1){
return 0;
}
if (arr[0]<arr[1]){
return 0;
}
if (arr[N-1]<arr[N-2]){
return N-1;
}
int L=0;
int R=N-1;
while (L<R-1){
int mid =L+(R+L)/2;
if (arr[mid]<arr[mid-1] && arr[mid]<arr[mid+1]){
return mid;
}else {
if (arr[mid]>arr[mid-1]){
R=mid-1;
}else {
L=mid+1;
}
}
}
return arr[L]<arr[R]?L:R;
}