题目描述
给定一个按照升序排列的整数数组 nums,和一个目标值 target。找出给定目标值在数组中的开始位置和结束位置。要求时间复杂度为O(log n),若数组中不存在目标值,返回[-1,1]。
用例
- 输入nums = [5,7,7,8,8,10], target = 8 输出[3,4]
- 输入nums = [5,7,7,8,8,10], target = 6 输出[-1,-1]
思路
- 看到升序数组,O(log n)立刻反应是二分查找。
- 要求查找数组中元素的第一个位置和最后一个位置,可以分为两步,先查找第一个位置,然后查找最后一个位置。
- 查找数组中元素的第一个位置,思路如下:首先使用二分法查找一次目标元素,记录查找到的目标元素下标为index,若index=-1,则表示未查找到。否则,继续在数组nums从0到index-1的范围内查找元素,若查找到,则更新index的值,然后继续在新的0到index-1范围内执行查找操作;若未查找到,则index即为元素的第一个位置。
- 查找最后一个元素操作类似。
代码
class Solution {
public int[] searchRange(int[] nums, int target) {
int[] res=new int[2];
res[0]=serachStart(nums, target);
res[1]=serachEnd(nums, target);
return res;
}
public int serachStart(int[] nums, int target){
int start=search(nums, target, 0, nums.length-1);
if(start==-1) return -1;
int temp=-1;
while(true){
temp=search(nums, target, 0, start-1);
if(temp==-1) break;
else start=temp;
}
return start;
}
public int serachEnd(int[] nums, int target){
int end=search(nums, target, 0, nums.length-1);
if(end==-1) return -1;
int temp=-1;
while(true){
temp=search(nums, target, end+1, nums.length-1);
if(temp==-1) break;
else end=temp;
}
return end;
}
public int search(int[] nums, int target, int low, int high){
int mid=-1;
while(low<=high){
mid=low+(high-low)/2;
if(nums[mid]==target) return mid;
else if(nums[mid]<target) low=mid+1;
else high=mid-1;
}
return -1;
}
}

1750

被折叠的 条评论
为什么被折叠?



