您的位置:首页 > 其它

Find Minimum in Rotated Sorted Array && Find Minimum in Rotated Sorted Array II

2014-11-08 16:30 525 查看
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.

You may assume no duplicate exists in the array.

主要思想是二分查找,对于num[beg .. end]数组,命mid=(beg+end)/2,那么存在一下三种情况:

1)num[beg]<num[end]: 这时,整个数组是有序的,因此直接返回num[beg]即可;

2)num[beg]>=num[end] && num[beg]>num[mid]:这时,num[mid..end]有序,那么最小值一定出现在num[beg..mid]之中,抛弃num[mid+1..end];

3)num[mid]>=num[end] && num[beg]<=num[mid] : 这时,num[beg..mid]是有序的,所以最小值一点个出现在num[mid+1..end]中,因为至少num[end]是小于num[beg]的,抛弃num[beg..mid];

public class Solution {
public int findMin(int[] num){
int len = num.length;
int beg = 0;
int end = len-1;
while(beg<end){

//all sorted
if(num[end]>=num[beg]){
break;
}
int mid = (beg+end)/2;

//Sorted from mid to end
//The smallest must in num[beg..mid]
if(num[mid]<num[beg]){
end = mid;
}
else{
//Sorted from beg to mid
//The smallest must in num[mid+1..end]
beg = mid+1;
}
}
return num[beg];
}
}


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.

第二道题目加入了一个条件,即允许出现重复元素,这里直接引用Solution中给提出的思想了。

For case where AL == AM == AR, the minimum could be on AM’s left or right side (eg, [1, 1, 1, 0, 1] or [1, 0, 1, 1, 1]). In this case, we could not discard either subarrays and therefore such worst case degenerates to the order of O(n).
public int findMin(int[] A) {
int L = 0, R = A.length - 1;
while (L < R && A[L] >= A[R]) {
int M = (L + R) / 2;
if (A[M] > A[R]) {
L = M + 1;
} else if (A[M] < A[L]) {
R = M;
} else {   // A[L] == A[M] == A[R]
L = L + 1;
}
}
return A[L];
}


我的代码如下:

public class Solution {
public int findMin(int[] num){
int len = num.length;
int beg = 0;
int end = len-1;

while(beg<end){
//all sorted
if(num[end]==num[beg]){
beg++;
continue;
}

if(num[end]>num[beg]){
break;
}
int mid = (beg+end)/2;

//Sorted from mid to end
//The smallest must in num[beg..mid]
if(num[mid]<num[beg]){
end = mid;
}
else{
//Sorted from beg to mid
//The smallest must in num[mid+1..end]
beg = mid+1;
}
}
return num[beg];
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: