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]
这个题的意思是在一个数组中寻找与target相等的两个数并返回位置,要求时间复杂度为O(Log n),则可以看出使用二分法进行求,但是需要做一点变形,因为两个数字相等的时候不适合二分。
1)
class Solution {
public int[] searchRange(int[] nums, int target) {
double left = target - 0.5, right = target + 0.5;
int l = bs(nums, left), r = bs(nums, right);
if(l == r) return new int[]{-1, -1};
return new int[]{l, r-1};
}
public int bs(int[] nums, double target) {
int l = 0, h = nums.length-1;
while(l <= h){
int m = l + (h - l)/2;
if(target > nums[m]) l = m+1;
else h = m-1;
}
return l;
}
}