题目
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]
十分钟尝试
根据时间复杂度可以看出来,利用两个指针方法,其中漏掉了一些情况:
1 p==q但是当前值不是target
2 循环条件不是p<q,因为无法终止,应该是值的比较作为循环条件并且p<q
3 if语句里面,也需要限定p<q,否则比如两个元素1 5 ,寻找4,一个while循环就会出现p>q的情况
class Solution {
public int[] searchRange(int[] nums, int target) {
int[] res=new int[2];
if(nums.length==0||target<nums[0]||target>nums[nums.length-1]){
res[0]=-1;
res[1]=-1;
return res;
}
int p=0;
int q=nums.length-1;
while(p<q&&(nums[p]<target||nums[q]>target)){
//需要增加p<q,否则1 5寻找4,会出现p>q没有来得及下次循环,本次就导致p>q
if(p<q&&nums[p]<target){
p++;
}
if(p<q&&nums[q]>target){
q--;
}
}
//如果相遇,并且不是target就是没有找到
if(p==q&&nums[q]!=target){
res[0]=-1;
res[1]=-1;
}
else{
res[0]=p;
res[1]=q;
}
return res;
}
}
其他解法
很多人利用二分查找去做,我写了下面的代码,发现有问题,这个是典型的二分查询代码,但是对于5 7 7 8 8 10的输入,如果找8,返回的是4,不确定是第一个还是最后一个索引。那么对于二分查询怎么确定查询的是start index还是end index呢?
private static int search(int[] nums, int target) {
int index = -1;
int low = 0;
int high = nums.length - 1;
while (low < high) {
int mid = low + (high - low) / 2;
if (nums[mid] == target) {
index = mid;
return index;
} else if (nums[mid] > target) {
high = mid - 1;
} else {
low = mid + 1;
}
}
return -1;
}