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

    Question

    Follow up for "Find Minimum in Rotated Sorted Array":
    What if duplicates are allowed?

    Would this affect the run-time complexity? How and why?
    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.

    The array may contain duplicates.

    Solution

    抓住数组的特点。

    Code

    class Solution {
    public:
        int findMin(vector<int>& nums) {
            int size = nums.size();
            if (size == 1)
                return nums[0];
            int low = 0;
            int high = size - 1;
            while (low < high) {
            	// 没用递归,所以注意求中间节点的方法
                int mid = low + (high - low) / 2;
                // 如果更小,那么会比右边的都小
                if (nums[mid] < nums[high])
                    high = mid;
                // 如果更大,那最小的肯定在右边
                else if (nums[mid] > nums[high])
                    low = mid + 1;
                // 如果相等,不知道最大值在左边还是在右边
                else
                    high--;
            }
            return nums[low];
        }
    };
    
  • 相关阅读:
    Java实现水仙花数
    CSS3属性选择器
    Word快捷键
    Java实现百钱买百鸡
    某专业人士给中国计算机专业学生的建议
    经典名言警句
    面试问题和思路
    情商
    Java注意的地方
    唯大英雄能真本色——Leo鉴书34
  • 原文地址:https://www.cnblogs.com/zhonghuasong/p/7620023.html
Copyright © 2011-2022 走看看