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

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];
	}
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值