• 154. Find Minimum in Rotated Sorted Array II


    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.

    Example 1:

    Input: [1,3,5]
    Output: 1

    Example 2:

    Input: [2,2,2,0,1]
    Output: 0

    Note:

    153. find minimum in rotated sorted array的follow up  https://www.cnblogs.com/fatttcat/p/10061983.html

    数组里可以有重复元素,还是一样用binary search

    如果array[mid] < array[right]说明最小值在mid的右侧,应该在mid的下一位开始找起;

    如果array[mid] > array[right]说明右边的数组是递增的,最小值在mid或mid的左侧,right = mid;

    如果array[mid] = array[right],减小数组长度,right--

    最后判断一下左右边界,谁小返回谁

    time: O(logn)  -- worst case O(n) if all elements are same, space: O(1)

    class Solution {
        public int findMin(int[] nums) {
            if(nums == null || nums.length == 0) return -1;
            int l = 0, r = nums.length - 1;
            while(l + 1 < r) {
                int m = l + (r - l) / 2;
                if(nums[m] > nums[r])
                    l = m + 1;
                else if(nums[m] < nums[r])
                    r = m;
                else
                    r--;
            }
            return nums[l] < nums[r] ? nums[l] : nums[r];
        }
    }
  • 相关阅读:
    js中有哪些是循环遍历的方法?
    堆内存和栈内存
    Html5和Css3
    PyCharm IDE 的使用
    python基础语法
    数据挖掘书籍简介
    寄存器-2
    汇编基础
    Std::bind()
    手游页游和端游的服务端框架
  • 原文地址:https://www.cnblogs.com/fatttcat/p/10142549.html
Copyright © 2020-2023  润新知