Given an array of integers 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]
.
For example,
Given [5, 7, 7, 8, 8, 10]
and target value 8,
return [3, 4]
.
不过自己最后有点绕进去了,因为两个相邻的数相加数/2总是偏小的那个数。。。 = =
public class Solution {
public int[] searchRange(int[] nums, int target) {
int[] ans = new int[]{-1, -1};
if(nums==null || nums.length==0) return ans;
int left = 0 , right = nums.length-1;
while(left<right){
int mid = (left+right)/2;
if(nums[mid]<target) left = mid + 1;
else right = mid;
}
if(nums[left]!=target) return ans;
ans[0] = left;
left = 0;
right = nums.length-1;
while(left<right){
int mid = (left+right)/2;
if(nums[mid]<=target) left = mid + 1;
else right = mid - 1;
}
if(nums[left]==target) ans[1] = left;
else ans[1] = left-1;
return ans;
}
}
可以在第二个mid求取时+1使其向右偏,可以省下面的判断
另一种求该数位置和该数+1位置的二分法思路
public class Solution {
public int[] searchRange(int[] A, int target) {
int start = Solution.firstGreaterEqual(A, target);
if (start == A.length || A[start] != target) {
return new int[]{-1, -1};
}
return new int[]{start, Solution.firstGreaterEqual(A, target + 1) - 1};
}
//find the first number that is greater than or equal to target.
//could return A.length if target is greater than A[A.length-1].
//actually this is the same as lower_bound in C++ STL.
private static int firstGreaterEqual(int[] A, int target) {
int low = 0, high = A.length;
while (low < high) {
int mid = low + ((high - low) >> 1);
//low <= mid < high
if (A[mid] < target) {
low = mid + 1;
} else {
//should not be mid-1 when A[mid]==target.
//could be mid even if A[mid]>target because mid<high.
high = mid;
}
}
return low;
}
}