[LC][array][binary search]153. Find Minimum in Rotated Sorted Array

一、问题描述

Suppose an array sorted in ascending order 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.


二、我的解法

因为暴力搜是O(n),所以问题可转化二分搜索。(假设在most cases下奏效~)

因为是排序过的rotated array,所以只有两种可能,一种是升序,一种是劈开,就像在两个象限。(见笔记)

找最小的数,就是找劈开后比较小的那段的第一个数。

那么怎么区分劈开的两段呢?一种方法是把nums第一个元素取出来,小于它的就属于比较小的那段;第二种是把nums最后一个元素当作bound,小于等于它的属于比较小的那段。但第一种方法的缺陷是如果nums没有劈开,而是升序,就不存在小于nums[0]的了。

代码:

class Solution {
    public int findMin(int[] nums) {
        if(nums == null || nums.length == 0){
            return -1;
        }
        
        int start = 0, end = nums.length -1;
        int mid;
        int bound = nums[end];
        
        while(start + 1 < end){
            mid = start + (end - start) / 2;
            if(nums[mid] <= bound){
                end = mid;
            }
            else{
                start = mid;
            }
        }
        if(nums[start] <= bound){
            return nums[start];
        }
        if(nums[end] <= bound){
            return nums[end];
        }
        return -1;
    }
}


三、其他解法

 int findMin(vector<int> &num) {
        int start=0,end=num.size()-1;
        
        while (start<end) {
            if (num[start]<num[end])
                return num[start];
            
            int mid = (start+end)/2;
            
            if (num[mid]>=num[start]) {
                start = mid+1;
            } else {
                end = mid;
            }
        }
        
        return num[start];
    }

In this problem, we have only three cases.

Case 1. The leftmost value is less than the rightmost value in the list: This means that the list is not rotated.
e.g> [1 2 3 4 5 6 7 ]

Case 2. The value in the middle of the list is greater than the leftmost and rightmost values in the list.
e.g> [ 4 5 6 7 0 1 2 3 ]

Case 3. The value in the middle of the list is less than the leftmost and rightmost values in the list.
e.g> [ 5 6 7 0 1 2 3 4 ]

As you see in the examples above, if we have case 1, we just return the leftmost value in the list. If we have case 2, we just move to the right side of the list. If we have case 3 we need to move to the left side of the list.

Following is the code that implements the concept described above.

”标红部分蛮好的,如果满足这个条件,说明start-end是单调的,可以直接结束。

具体的判断条件什么的还需要再深入思考一下。

四、总结反思

这题属于二分法的变种。判断条件不是直接的判断中点==target,而是转化为了判断它是否小于一个数。

二分法的精髓在于每次通过一个条件(不一定是相等),把问题规模缩小一半。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值