zoukankan      html  css  js  c++  java
  • 154. Find Minimum in Rotated Sorted Array II

    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.

     与Find Minimum in Rotated Sorted Array类似,可以和nums[left]比,也可以和nums[right]比,代码如下:

     1 public class Solution {
     2     public int findMin(int[] nums) {
     3         if(nums==null||nums.length==0) return -1;
     4         int low = 0;
     5         int high = nums.length-1;
     6         while(low < high) {
     7             int mid = low + (high - low) / 2;
     8             if(nums[low] < nums[high]) return nums[low];
     9             else if(nums[low] < nums[mid]) low = mid + 1;
    10             else if(nums[low] > nums[mid]) high = mid;
    11             else low++;
    12         }
    13         return nums[low];
    14     }
    15 }
    16 // the run time complexity could be two cases. the average case could be logn, the worst case could be O(n), the space complexity could be O(1);

    public class Solution {

        public int findMin(int[] nums) {

            int left=  0;

            int right = nums.length-1;

            while(left<right){

                int mid = left+(right-left)/2;

                if(nums[mid]<nums[right]){

                    right = mid;

                }else if(nums[mid]>nums[right]){

                    left = mid+1;

                }else{

                    right--;

                }

            }

            return nums[left];

        }

    }

  • 相关阅读:
    list(range(10))解释
    numpy.random.normal函数
    适用于Python扩展程序包的非官方Windows二进制文件
    Linux--vi/vim编辑器常用命令
    Centos Mirrors List (centos7)
    windows--redis安装
    Celery 3.x 升级至 celery 4.x(转)
    windows/linux(centos7)安装SVN
    远程获取--snmp模块(python)/snmp-cmds,easysnmp
    FileZilla客户端(OS)连接Linux
  • 原文地址:https://www.cnblogs.com/codeskiller/p/6359741.html
Copyright © 2011-2022 走看看