package com.example.leetcode;
public class _704二分查找_右边界 {
public static int search(int[] nums, int target) {
int left = 0;
int right = nums.length - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (target == nums[mid]) {
left = mid + 1; // todo 与常规不同的,往右边找
} else if (target > nums[mid]) {
left = mid + 1;
} else if (target < nums[mid]) {
right = mid - 1;
}
}
if (right < 0 || left >= nums.length || nums[right] != target) {
return -1;
}
return right;
}
public static void main(String[] args) {
int[] nums = {1, 1, 7, 7, 30};
int search = search(nums, 7);
System.out.println(search);
}
}
09-30
1008
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
11-21
2551
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
07-24
852
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)