LeetCode 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.

【题解】

本题有两种做法:

1、由于数组是在排好序后旋转的,故只需从头到尾扫描一次,若当前的元素比前次的元素小时,便找到了最小的元素,时间复杂度为O(n)

2、另一种做法是使用改版的二分查找,当中间的元素小于当前循环最右边的元素时,最右边的边界设置为中间元素的索引;当间的元素大于当前循环最右边的元素时,最左边的边界设置为中间元素的索引加1。循环的条件是最左边的元素大于最右边的元素,时间复杂度为O(lgn)

【代码】

O(n)算法:

    int findMin(vector<int>& nums) {
        int nResult = nums[0];
        int nSize = nums.size();
        
        int nPre = nums[0];
        for (int i = 1; i < nSize; i++) {
            if (nums[i] < nPre) {
                nResult = nums[i];
                break;
            }
            nPre = nums[i];
        }
        
        return nResult;
    }

O(lgn)算法:

    int findMin(vector<int>& nums) {
        int nSize = nums.size();
        if (nSize == 1)
            return nums[0];
        
        int nLeft = 0;
        int nRight = nSize - 1;
        while (nums[nLeft] > nums[nRight]) {
            int nMid = (nLeft + nRight)/2;
            if (nums[nMid] < nums[nRight])
                nRight = nMid;
            else
                nLeft = nMid + 1;
        }
        
        return nums[nLeft];
    }


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值