算法-二分查找-1

普通二分查找


public static int search(int[] arr, int target) {
int l = 0;
int r = arr.length;
while (l < r) {
int mid = l + ((r - l) >> 1);
if (arr[mid] < target) {
l = mid + 1;
} else if (arr[mid] > target) {
r = mid - 1;
} else {
return mid;
}
}
return -1;
}
 

找到第一次出现的目标值下标

 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 }

 

posted @ 2021-08-02 09:31  rudynan  阅读(27)  评论(0编辑  收藏  举报