leetcode 之Find Minimum in Rotated Sorted Array

来源:互联网 发布:mac chrome 书签备份 编辑:程序博客网 时间:2024/06/05 00:33

问题:

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.

思路:用binary search, 一半是有序的,一半是无序的。minimum在无序的子数组中。


class Solution {public:    int findMin(vector<int> &num) {        int start = 0;        int end = num.size() - 1;        int middle;        while(start < end) {            //not reverse, return.            if(num[start] < num[end])                return num[start];            middle = (start + end )/ 2;            if(num[middle] >= num[start])            {                start = middle + 1;            }else{                end = middle;                start += 1;            }        }        return num[end];    }};


0 0
原创粉丝点击