• 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];
        }
    };
    
  • 相关阅读:
    Ubuntu设置文件默认打开方式
    车险与费用计算(仅做参考)
    房贷计算
    PHP敏感词处理
    记一次,接口pending
    layer confirm确认框,多个按钮
    crontab vim 模式
    git指定迁出目录
    mysql树形结构
    Kubeflow实战: 入门介绍与部署实践
  • 原文地址:https://www.cnblogs.com/zhonghuasong/p/7620023.html
Copyright © 2020-2023  润新知