[Leet code 153, medium] Find Minimum in Rotated Sorted Array

Problem:

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.

Solutions:

This is a typical problem that can be used using binary search algorithm. Note that the rotated sorted array must be longer than 3. The exceptional cases, i.e. the subarray of size 2 or smaller, should be dealt with seperately. Another point of this problem is the input array does not include duplicates. The case when the array contains duplicates will be dealt with in the problem 154.


    int findMin(vector<int> &num) {
        if(num.size() == 1)
            return num[0];

        int iStart = 0, iEnd = num.size() - 1;
        for(int iMiddle = (iEnd + iStart + 1)/2; iStart != iEnd; iMiddle = (iEnd + iStart + 1)/2) {
            if(num[iStart] < num[iEnd])
                return num[iStart];

            if(iStart == iEnd - 1)
                return (num[iStart] < num[iEnd] ? num[iStart] : num[iEnd] );

            if(num[iStart] < num[iMiddle]) {
                if(num[iMiddle] > num[iMiddle + 1])
                    return num[iMiddle + 1];
                else
                    iStart = iMiddle + 1;
            } else {
                if(num[iMiddle] < num[iMiddle - 1])
                    return num[iMiddle];
                else
                    iEnd = iMiddle - 1;
            }
        }
        
    }


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值