Follow up for "Find Minimum in Rotated Sorted Array":
What if duplicates are allowed?Would this affect the run-time complexity? How and why?
Suppose a sorted array is rotated at some pivot unknown to you beforehand.
(i.e.,
0 1 2 4 5 6 7
might become 4 5 6 7 0 1 2
).
Find the minimum element.
The array may contain duplicates.
Answer:
public class Solution {
public int findMin(int[] num) {
int start=0, end=num.length-1;
while(start+1 < end){ //ensure: start != mid != end
int mid = start + (end-start)/2;
if(num[mid] < num[end]){
end = mid;
}
else if(num[mid] > num[end]){
start = mid;
}
else{ //num[mid] == num[end], like [3 3 1 3]
int endtmp = end-1;
while(endtmp>mid && num[endtmp]==num[end]){
endtmp--;
}
if(num[endtmp] != num[mid]){ //there existeds peak point in the range!
start = mid;
}
else{
end = mid; //include case: endtmp==mid, there are no peak point in the range!
}
}
}
//start = end - 1
if(num[start]<=num[end]){
return num[start];
}
return num[end];
}
}
No comments:
Post a Comment