-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFindNumber.java
More file actions
33 lines (31 loc) · 1.12 KB
/
FindNumber.java
File metadata and controls
33 lines (31 loc) · 1.12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
package leetcode.array;
/**
* @ClassName FindNumber
* @Description 在排序数组中查找元素的第一个和最后一个位置
* https://leetcode-cn.com/problems/find-first-and-last-position-of-element-in-sorted-array/
* @Author changxuan
* @Date 2020/12/1 下午9:50
**/
public class FindNumber {
public int[] searchRange(int[] nums, int target) {
int leftIdx = binarySearch(nums, target, true);
int rightIdx = binarySearch(nums, target, false) - 1;
if (leftIdx <= rightIdx && rightIdx < nums.length && nums[leftIdx] == target && nums[rightIdx] == target) {
return new int[]{leftIdx, rightIdx};
}
return new int[]{-1, -1};
}
public int binarySearch(int[] nums, int target, boolean lower) {
int left = 0, right = nums.length - 1, ans = nums.length;
while (left <= right) {
int mid = (left + right) / 2;
if (nums[mid] > target || (lower && nums[mid] >= target)) {
right = mid - 1;
ans = mid;
} else {
left = mid + 1;
}
}
return ans;
}
}