Find Minimum in Rotated Sorted Array II

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.

 

 1 public class Solution {
 2     public int findMin(int[] num) {
 3         if(num == null || num.length == 0) return 0;
 4         int min = Integer.MAX_VALUE;
 5         int str = 0, end = num.length - 1;
 6         while(str <= end){
 7             if(num[str] == num[end]){
 8                 int tmp = num[str];
 9                 min = min > tmp ? tmp : min;
10                 while(str < end && num[str] == tmp) str ++;
11                 while(str < end && num[end] == tmp) end --;
12             }
13             int mid = (str + end) / 2;
14             min = min > num[mid] ? num[mid] : min;
15             if(num[mid] < num[end]){
16                 end = mid;
17             }else if(num[mid] == num[end]){//from mid to end all the number is same
18                 end = mid - 1;
19             }else{
20                 str = mid + 1;
21             }
22         }
23         return min;
24     }
25 }

 

posted on 2014-10-23 09:27  Step-BY-Step  阅读(162)  评论(0编辑  收藏  举报

导航