Binary Search 相关的case

Case 1: 在一个sorted array里面找出target value的 index,如果target value 出现了多次,返回任何一个就可以了。

Cas 2:  Find the smallest number which is greater than the target

 

Case 3: Find the largest number which is smaller than the target

Case 4: Find the left most index of the target value in the sorted array. If not found, return the index of the smallest number which is greater than the target.

 1     private static int leftMostIndex(int[] arr, int target) {
 2         int left = 0, right = arr.length - 1;
 3         while (left <= right) {
 4             int mid = left + (right - left) / 2;
 5             if (arr[mid] < target) {
 6                 left = mid + 1;
 7             } else {
 8                 right = mid - 1;
 9             }
10         }
11         return left;
12     }

 Case 4: Find the right most index of the target value in the sorted array. If not found, return the index of the largest number which is smaller than the target.

 1     private static int rightMostIndex(int[] arr, int target) {
 2         int left = 0, right = arr.length - 1;
 3         while (left <= right) {
 4             int mid = left + (right - left) / 2;
 5             if (arr[mid] <= target) {
 6                 left = mid + 1;
 7             } else {
 8                 right = mid - 1;
 9             }
10         }
11         return right;
12     }

 

posted @ 2021-03-07 10:03  北叶青藤  阅读(59)  评论(0)    收藏  举报