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 }
原文:https://www.cnblogs.com/beiyeqingteng/p/14493707.html