zoukankan      html  css  js  c++  java
  • 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.

     class Solution {  
    public:  
        int findMin(vector<int> &num) {  
            int start = 0;  
            int end = num.size() - 1;  
            int mid = 0;  
            while (start < end) { //注意这里和普通的二分查找不同,这里是start < end不是 start <= end.  
                    mid = start + (end - start)/2;  
                    if (num[mid] > num[end])  
                        start = mid + 1; //此时可以扔掉mid的值  
                    else   
                        end = mid;//此时不能扔掉mid的值  
            }  
            return num[end]; //退出循环说明start与end相等,所以只剩一个元素可能,所以return [start]或者return [end]都可以了。  
            //注意不能return mid,可以从{2,1}这个输入看出来。  
              
        }  
    };
     
  • 相关阅读:
    换教室
    [国家集训队]礼物
    【模板】扩展卢卡斯(学习笔记)
    Desert King
    绿豆蛙的归宿
    Dropping tests
    [SDOI2013]随机数生成器
    佳佳的fib
    [USACO10OPEN]水滑梯Water Slides
    强大的XML
  • 原文地址:https://www.cnblogs.com/simplepaul/p/7685713.html
Copyright © 2011-2022 走看看