Given an array of integers nums
sorted in ascending order, find the starting and ending position of a given target
value.
Your algorithm's runtime complexity must be in the order of O(log n).
If the target is not found in the array, return [-1, -1]
.
Example 1:
Input: nums = [5,7,7,8,8,10], target = 8 Output: [3,4]
Example 2:
Input: nums = [5,7,7,8,8,10], target = 6 Output: [-1,-1]
二分查找
找到后左右搜寻
class Solution {
public int[] searchRange(int[] nums, int target) {
if(nums.length==0)
return new int[]{-1,-1};
int start=0;
int end=nums.length-1;
while(start<=end){
int mid=(start+end)/2;
if(target==nums[mid]){
int left=mid;
int right=mid;
while(left>0 && nums[left-1]==nums[mid]){
left--;
}
while(right<nums.length-1 && nums[right+1]==nums[mid]){
right++;
}
return new int[]{left,right};
}
if(target<nums[mid] && target>=nums[0]){
end=mid-1;
}
else{
start=mid+1;
}
}
return new int[]{-1,-1};
}
}
或
直接判断
class Solution {
// returns leftmost (or rightmost) index at which `target` should be
// inserted in sorted array `nums` via binary search.
private int extremeInsertionIndex(int[] nums, int target, boolean left) {
int lo = 0;
int hi = nums.length;
while (lo < hi) {
int mid = (lo + hi) / 2;
if (nums[mid] > target || (left && target == nums[mid])) {
hi = mid;
}
else {
lo = mid+1;
}
}
return lo;
}
public int[] searchRange(int[] nums, int target) {
int[] targetRange = {-1, -1};
int leftIdx = extremeInsertionIndex(nums, target, true);
// assert that `leftIdx` is within the array bounds and that `target`
// is actually in `nums`.
if (leftIdx == nums.length || nums[leftIdx] != target) {
return targetRange;
}
targetRange[0] = leftIdx;
targetRange[1] = extremeInsertionIndex(nums, target, false)-1;
return targetRange;
}
}
线性扫描
首先,我们对 nums 数组从左到右做线性遍历,当遇到 target 时中止。如果我们没有中止过,那么 target 不存在,我们可以返回“错误代码” [-1, -1] 。如果我们找到了有效的左端点坐标,我们可以坐第二遍线性扫描,但这次从右往左进行。这一次,第一个遇到的 target 将是最右边的一个(因为最左边的一个存在,所以一定会有一个最右边的 target)。我们接下来只需要返回这两个坐标。
class Solution {
public int[] searchRange(int[] nums, int target) {
int[] targetRange = {-1, -1};
// find the index of the leftmost appearance of `target`.
for (int i = 0; i < nums.length; i++) {
if (nums[i] == target) {
targetRange[0] = i;
break;
}
}
// if the last loop did not find any index, then there is no valid range
// and we return [-1, -1].
if (targetRange[0] == -1) {
return targetRange;
}
// find the index of the rightmost appearance of `target` (by reverse
// iteration). it is guaranteed to appear.
for (int j = nums.length-1; j >= 0; j--) {
if (nums[j] == target) {
targetRange[1] = j;
break;
}
}
return targetRange;
}
}