您的位置:首页 > 其它

Leetcode-Find Minimum in Rotated Sorted Array II

2014-11-22 04:10 344 查看

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:

public class Solution {
public int findMin(int[] num) {
if (num.length==0) return -1;
int start = 0, end = num.length-1;
int min = findMinRecur(num,start,end);
return min;
}

//NOTE: We need to consider the ending case that start==end, this happens when there is only one element in the array!
public int findMinRecur(int[] num, int start, int end){
if (start==end-1 || start==end){
if (num[start]<num[end]) return num[start];
else return num[end];
}

int mid = (start+end)/2;
int min = Integer.MAX_VALUE;
if (num[mid]<num[start]){
min = findMinRecur(num,start,mid);
return min;
}

if (num[mid]>num[end]){
start = mid;
min = findMinRecur(num,mid,end);
return min;
}

if (num[mid]==num[start] && num[mid]==num[end]){
int min1 = findMinRecur(num,start,mid);
int min2 = findMinRecur(num,mid,end);
if (min1<min2) return min1;
else return min2;
}

if (num[start]>num[end]) return num[end];
else return num[start];
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: