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.
Idea: Consider the worst case as [2,1,2,2,2,2,2,....,2]. Binary search can not tell which half contains the minimum. Therefore just scan from left to right to get the minimum.
Time: O(n) Space: O(1)
Code:
public class Solution {
public int findMin(int[] num) {
int result=Integer.MAX_VALUE;
for(int i:num)
result=Math.min(result,i);
return result;
}
}
不能这么搞的吧。应该要用二分的吧。
ReplyDelete