Leetcode:34 题目描述: 给定一个按照升序排列的整数数组 nums,和一个目标值 target。找出给定目标值在数组中的开始位置和结束位置。
如果数组中不存在目标值 target,返回 [-1, -1]。
进阶:设计时间复杂度为O(log n)
拆分成左右边界
示例1:
右边界
left = 0,right = 5 ->mid = 0 + 2 = 2
left = 3,right = 5 ->mid = 3 + 1 = 4
left = 5(r_B),right = 5 ->mid = 5
left = 5(r_B),right = 4,跳出找到r_B
左边界
left = 0,right = 5 ->mid = 0 + 2 = 2
left = 3.right = 5 ->mid = 3+ 1 = 4
left = 3,right = 3(l_B)->mid = 3
left = 3,right = 2(L_B),跳出
即:L_B=2.r_B=5
class Solution {
int[] searchRange(int[] nums, int target) {
int leftBorder = getLeftBorder(nums, target);
int rightBorder = getRightBorder(nums, target);
if (leftBorder == -2 || rightBorder == -2) return new int[]{-1, -1};
if (rightBorder - leftBorder > 1) return new int[]{leftBorder + 1, rightBorder - 1};
return new int[]{-1, -1};
}
int getRightBorder(int[] nums, int target) {
int left = 0;
int right = nums.length - 1;
int rightBorder = -2;
while (left <= right) {
int middle = left + ((right - left) / 2);
if (nums[middle] > target) {
right = middle - 1;
} else {
left = middle + 1;
rightBorder = left;
}
}
return rightBorder;
}
int getLeftBorder(int[] nums, int target) {
int left = 0;
int right = nums.length - 1;
int leftBorder = -2;
while (left <= right) {
int middle = left + ((right - left) / 2);
if (nums[middle] >= target) {
right = middle - 1;
leftBorder = right;
} else {
left = middle + 1;
}
}
return leftBorder;
}
}
|