目录

题目描述:

假设按照升序排序的数组在预先未知的某个点上进行了旋转。

SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。

( 例如,数组 [0,1,2,4,5,6,7] 可能变为 [4,5,6,7,0,1,2] )。

请找出其中最小的元素。

你可以假设数组中不存在重复元素。

示例 1:

输入: [3,4,5,1,2]
输出: 1

示例 2:

输入: [4,5,6,7,0,1,2]
输出: 0

解法:

class Solution {
public:
    int findMin(vector<int>& nums) {
        // to find the rotated point
        int sz = nums.size();
        if(sz == 0){
            return -1;
        }else if(sz == 1){
            return nums[0];
        }else{
            int l = 0, r = sz-1;
            if(nums[l] < nums[r]){
                // the whole list is ascend
                return nums[l];
            }
            int mid = 0;
            while(r - l > 1){   // loop untill left two elements
                mid = l + (r - l)/2;
                // only two cases: left part ascend or right part ascend
                if(nums[mid] > nums[l]){
                    l = mid;
                }else if(nums[mid] < nums[r]){
                    r = mid;
                }
            }
            return min(nums[l], nums[r]);
        }
    }
};
扫码关注我们
微信号:SRE实战
拒绝背锅 运筹帷幄