好好好,又是log n那么还有什么说的,非递减顺序排列
二分法启动
class Solution {
public int[] searchRange(int[] nums, int target) {
int left = 0, right = nums.length - 1;
int[] result = new int[2];
int[] bad = { -1, -1 };
while (left <= right) {
int mid = (left + right) >> 1;
if (nums[mid] == target) {
// 找左边界
int low = mid;
while (low >= 0 && nums[low] == target) {
low--;
}
result[0] = low + 1;
// 找右边界
int high = mid;
while (high < nums.length && nums[high] == target) {
high++;
}
result[1] = high - 1;
return result;
} else if (nums[mid] > target) {
right = mid - 1;
} else {
left = mid + 1;
}
}
return bad;
}
}
注意这里找mid的时候,数组是十分容易超出界限的,所以一旦涉及+1或者-1进行前置判断,判断是否会超出界限后再进行