LeetCode 34. 【Java】34. Find First and Last Position of Element in Sorted Array
原题链接
中等
作者:
tt2767
,
2020-01-05 15:38:26
,
所有人可见
,
阅读 907
// 1. 单调-> 二分
// 2. bound:【0~end-1】,
// 3. check: MAX(x <= nums[i]) , MIN(x >= num[i])
// 4. 特判:
class Solution {
public int[] searchRange(int[] nums, int target) {
if (nums == null || nums.length == 0 || target < nums[0] || nums[nums.length-1] < target) return new int[]{-1, -1};
int l = 0, r = nums.length-1;
int start;
while (l < r){
int mid = (l+r) >> 1;
if (nums[mid] >= target) r = mid;
else l = mid+1;
}
if (nums[l] != target) return new int[]{-1, -1};
else start = l;
l = 0;
r= nums.length -1;
while(l < r){
int mid = (l+r+1) >> 1;
if (nums[mid] <= target) l = mid;
else r = mid -1;
}
return new int[]{start, l};
}
}