zoukankan      html  css  js  c++  java
  • Leetcode- Find Minimum in Rotated Sorted Array-ZZ

    http://changhaz.wordpress.com/2014/10/15/leetcode-find-minimum-in-rotated-sorted-array/

    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.

    Solution:
    Classic binary search problem. One place worth noticing is the termination conditions. Whenever our window has only one element, its value is the answer. When our window has two elements, and the first element is larger than the second one, the second element is our answer. This case falls into the num[mid]>=num[start] condition in the code below. (given that there is no duplicates in the array)

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    class Solution {
    public:
        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];
        }
    };
     
  • 相关阅读:
    便 加权并查集
    bzoj 4565 状压区间dp
    bzoj 2242 [SDOI2011]计算器 快速幂+扩展欧几里得+BSGS
    poj 3243 扩展BSGS
    bzoj 3239 poj 2417 BSGS
    51nod 1135 原根 就是原根...
    bzoj 2005 能量采集 莫比乌斯反演
    约会 倍增lca
    bzoj 2186 [Sdoi2008]沙拉公主的困惑 欧拉函数
    IE下textarea去除回车换行符
  • 原文地址:https://www.cnblogs.com/forcheryl/p/4032278.html
Copyright © 2011-2022 走看看