美文网首页
153. Find Minimum in Rotated Sor

153. Find Minimum in Rotated Sor

作者: 留十夜 | 来源:发表于2017-08-03 14:47 被阅读0次

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.

建立两个指针:start end
start 位于前增序列(一种特殊情况是start 由于+1进入到后增序列的起始位置,应当返回)
end 位于后增序列

    int findMin(vector<int> &num) {
        int start=0,end=num.size()-1;
        
        while (start<end) {
            if (num[start]<num[end])
                return num[start];
            
            int mid = (start+end)/2;
            
            if (num[mid]>=num[start]) {
                start = mid+1;
            } else {
                end = mid;
            }
        }
        
        return num[start];
    }

相关文章

网友评论

      本文标题:153. Find Minimum in Rotated Sor

      本文链接:https://www.haomeiwen.com/subject/ucjplxtx.html