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];

        }

    }

  • 相关阅读:
    连接过滤器
    插件使用 之 Bmap
    插件使用 之 ztree、nicescroll
    插件使用 之 layui、echart
    插件使用 之 bootstrap
    jquery显隐特效 动画 事件
    jquery js对比 加载 操作内容 属性 样式 元素 选择器
    js三级联动练习(地址填写)
    js时间、定时器、移动div块、轮播
    js DOM操作
  • 原文地址:https://www.cnblogs.com/codeskiller/p/6359741.html
Copyright © 2011-2022 走看看