题目
数组中找目标数组存在的范围
1 二分查找的变形,能够做到平均时间的O(lgn)
public class Solution {
public int[] searchRange(int[] A, int target) {
int[] ans = new int[2];
ans[0]=-1;
ans[1]=-1;
if(A.length==0){
return ans;
}
int n = A.length;
int start =0;
int end = n-1;
while(start<=end){
int mid = start + (end -start)/2;
if(A[mid]==target){
int test = mid;
while(test>=start && A[test]==target){
test--;
}
ans[0]=test+1;
test = mid;
while(test<=end && A[test]==target){
test++;
}
ans[1]=test-1;
return ans;
}
else if(A[mid]>target){
end = mid-1;
}
else{
start = mid+1;
}
}
return ans;
}
}
15.3.12
public class Solution {
public int[] searchRange(int[] A, int target) {
int[] ans = {-1,-1};
if(A == null || A.length == 0){
return ans;
}
int n = A.length;
ans[0]= searchLeft(A,target,0,n-1);
ans[1]=searchRight(A,target,0,n-1);
return ans;
}
public int searchLeft(int[] A, int target,int start,int end){
int ans = -1;
while(start<=end){
int mid = start + (end-start)/2;
if(A[mid] == target){
ans = mid;
end = mid-1;
}
else if(A[mid] > target){
end = mid-1;
}
else{
start = mid+1;
}
}
return ans;
}
public int searchRight(int[] A, int target,int start,int end){
int ans = -1;
while(start<=end){
int mid = start + (end-start)/2;
if(A[mid] == target){
ans = mid;
start = mid+1;
}
else if(A[mid] > target){
end = mid-1;
}
else{
start = mid+1;
}
}
return ans;
}
}
要做到完全log(n),分解为两部,找到target最左边部分,找到target最右边部分。