普通二分查找
1 public int binarySearch(int[] arr, int target) { 2 int l = 0; 3 int r = arr.length - 1; 4 int mid = l + ((r - l) >> 1); 5 while (l <= r) { 6 if (arr[mid] < target) { 7 l = mid + 1; 8 } else if (arr[mid] > target) { 9 r = mid - 1; 10 } else { 11 return mid; 12 } 13 } 14 return -1; 15 }
找到第一次出现的目标值下标
1 public int search(int[] arr, int target) { 2 int l = 0; 3 int r = arr.length; 4 while (l < r) { 5 int mid = l + ((r - l) >> 1); 6 if (arr[mid] == target) { 7 r = mid; 8 } else if (arr[mid] < target) { 9 l = mid + 1; 10 } else { 11 r = mid; 12 } 13 } 14 if (l == arr.length) { 15 return -1; 16 } 17 return arr[l] == target ? l : -1; 18 }
找到最后出现的目标值下标
1 public int search(int[] arr, int target) { 2 int l = 0; 3 int r = arr.length; 4 while (l < r) { 5 int mid = l + ((r - l) >> 1); 6 if (arr[mid] == target) { 7 l = mid + 1; 8 } else if (arr[mid] < target) { 9 l = mid + 1; 10 } else { 11 r = mid; 12 } 13 }
// 因为l比目标值后移一位所以判断l==arr.length不能使用 坐标也不可能到0 14 if (l == 0) { 15 return -1; 16 } 17 return arr[l - 1] == target ? l - 1 : -1; 18 }