码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode-Find Minimum in Rotated Sorted Array II

时间:2014-11-22 07:03:46      阅读:206      评论:0      收藏:0      [点我收藏+]

标签:style   blog   io   ar   color   os   sp   for   on   

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.

Analysis:

For this problem, if we find that num[start]==num[mid]==num[end], we have to search both the left part and right part, because we do not know the min value is in which part. For example: 4 4 4 4 4 1 2 3 4 and 4 1 2 3 4 4 4 4 4.

Solution:

 1 public class Solution {
 2     public int findMin(int[] num) {
 3         if (num.length==0) return -1;
 4         int start = 0, end = num.length-1;
 5         int min = findMinRecur(num,start,end);
 6         return min;
 7     }
 8     
 9     //NOTE: We need to consider the ending case that start==end, this happens when there is only one element in the array!
10     public int findMinRecur(int[] num, int start, int end){
11         if (start==end-1 || start==end){
12             if (num[start]<num[end]) return num[start];
13             else return num[end];
14         }
15         
16         int mid = (start+end)/2;
17         int min = Integer.MAX_VALUE;
18         if (num[mid]<num[start]){
19             min = findMinRecur(num,start,mid);
20             return min;
21         }
22 
23         if (num[mid]>num[end]){
24             start = mid;
25             min = findMinRecur(num,mid,end);
26             return min;
27         }
28         
29         if (num[mid]==num[start] && num[mid]==num[end]){
30             int min1 = findMinRecur(num,start,mid);
31             int min2 = findMinRecur(num,mid,end);
32             if (min1<min2) return min1;
33             else return min2;
34         }
35         
36         if (num[start]>num[end]) return num[end];
37         else return num[start];
38     }
39 }

 

Leetcode-Find Minimum in Rotated Sorted Array II

标签:style   blog   io   ar   color   os   sp   for   on   

原文地址:http://www.cnblogs.com/lishiblog/p/4114637.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!