• LeetCode: Find Minimum in Rotated Sorted Array


    Title:

    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.

    class Solution {
    public:
        int findMin(vector<int>& nums) {
            int left = 0;
            int right = nums.size()-1;
            while (left < right && nums[left] > nums[right]){
                int mid = (left + right) / 2;
                if (nums[mid] < nums[left])
                    right = mid;
                else 
                    left = mid + 1;
            }
            return nums[left];
        }
    };

    II

    The array may contain duplicates.

    只需要修改while语句,并添加一个if语句。 [1,0,1,1,1]

    class Solution {
    public:
        int findMin(vector<int>& nums) {
            int left = 0;
            int right = nums.size()-1;
            while (left < right && nums[left] >= nums[right]){
                int mid = (left + right) / 2;
                if (nums[mid] < nums[left])
                    right = mid;
                else if (nums[mid] > nums[left])
                    left = mid+1;
                else 
                    left += 1;
            }
    		return nums[left];
        }
    };
    

      

  • 相关阅读:
    mysql timeout expired处理
    Git学习笔记(0)-错误汇总
    auto_ptr源码剖析
    谈谈工作中遇到的系统优化问题
    js 面向对象
    js API
    js 闭包
    js 重载(overload)
    css 文本单行、多行超出省略
    es6 字符串String的扩展
  • 原文地址:https://www.cnblogs.com/yxzfscg/p/4530399.html
Copyright © 2020-2023  润新知