Search for a Range
Total Accepted: 6500 Total Submissions: 24600 My Submissions
Given a sorted array of integers, 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].
时间复杂度是O(log n),二分查找呗。像这种如果笨办法扫描,大数据肯定过不了的。
如果使用二分查找法,找到target的话,还需要往前和往后扫描求边界,最坏也就是都扫描到头和尾。
Total Accepted: 6500 Total Submissions: 24600 My Submissions
Given a sorted array of integers, 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].
时间复杂度是O(log n),二分查找呗。像这种如果笨办法扫描,大数据肯定过不了的。
如果使用二分查找法,找到target的话,还需要往前和往后扫描求边界,最坏也就是都扫描到头和尾。
Java AC
public class Solution {
public int[] searchRange(int[] A, int target) {
int len = A.length;
if(target < A[0] && target > A[len-1]){
return new int[]{-1,-1};
}
int low = 0;
int high = len-1;
int mid = 0;
boolean flag = false;
while(low <= high){
mid = (low + high) >> 1;
if(A[mid] > target){
high = mid - 1;
}else if(A[mid] < target){
low = mid + 1;
}else{
flag = true;
break;
}
}
int array[] = new int[2];
array[0] = -1;
array[1] = -1;
if(flag){
int tempMid = mid;
while(tempMid+1 < len && A[tempMid+1] == target){
tempMid++;
}
array[1] = tempMid;
tempMid = mid;
while(tempMid-1 >= 0 && A[tempMid-1] == target){
tempMid--;
}
array[0] = tempMid;
}
return array;
}
}