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.

思路:这题目炸一看O(n)扫一遍不就行了吗,但作为程序员的我们要写出最优的代码。分析一下可以知道数列的走势是这样的。
1

那么显然二分一下就可以了,每次比较中值和右边的值。见代码。

class Solution {
public:
    int findMin(vector<int>& nums) {
        int r = nums.size() - 1;
        int l = 0;
        while (l < r) {
            int mid = (r - l)/2 + l;
            if (nums[mid] < nums[r]) r = mid;
            else l = mid + 1;
        }
        return nums[l];
    }
};
posted on 2018-03-10 21:32  Beserious  阅读(141)  评论(0编辑  收藏  举报