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

        }

    }

  • 相关阅读:
    jQuery 基本选择器
    JavaScriptif while for switch流程控制 JS函数 内置对象
    JavaScrip基本语法
    数据库 存储引擎 表的操作 数值类型 时间类型 字符串类型 枚举集合 约束
    数据库基础知识 管理员 用户登录授权的操作
    粘包的产生原理 以及如何解决粘包问题
    socket TCP DPT 网络编程
    2018年年终总结
    Android技术分享
    No accelerator found
  • 原文地址:https://www.cnblogs.com/codeskiller/p/6359741.html
Copyright © 2020-2023  润新知