zoukankan      html  css  js  c++  java
  • LeetCode Find Minimum in Rotated Sorted Array

    1.题目


    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.



    2.解决方式


    class Solution {
    public:
        int findMin(vector<int> &num) {
            if(num[0] <= num[num.size() - 1]){
                return num[0];
            }
            
            int leftIndex = 0;
            int rightIndex = num.size() - 1;
            
            
            while((leftIndex + 1) < rightIndex){
                int midIndex = (leftIndex + rightIndex) / 2;
                if(num[midIndex] < num[leftIndex]){
                    rightIndex = midIndex;
                }else{
                    leftIndex = midIndex;
                }
            }
             return min(num[leftIndex], num[rightIndex]);
            
        }
    };

    思路:假设是N的时间复杂度肯定太慢了。能够用二分查找。

    这个跟二分查找的不同之处是,while里面的推断方式,这样能够留下两个数。由于我们也不知道到底谁比較小。所以最后还要再找到最小的值。


    http://www.waitingfy.com/archives/1630


  • 相关阅读:
    电源
    SM2947
    网表
    cadence设计思路
    青山依旧在,几度夕阳红
    乐观锁与悲观锁
    笔记
    强弱软虚引用
    缓存相关
    dubbo
  • 原文地址:https://www.cnblogs.com/yfceshi/p/6755284.html
Copyright © 2011-2022 走看看