• LC.153.Find Minimum in Rotated Sorted Array


    https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/description/
    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.

    You may assume no duplicate exists in the array.
    注意,我们要找的最小值,只会在右端,所以如果已经在右端,则挪RIGHT
    如果在左端,则挪LEFT 往右端的深沟走

    time: o(logn) space: o(1)

     1 public int findMin(int[] nums) {
     2         if (nums ==null || nums.length ==0) return -1 ;
     3         int left = 0, right = nums.length -1 ;
     4         while(left + 1 < right){
     5             int mid = left +(right-left)/2 ;
     6             //lower part
     7             if (nums[mid]<nums[right]){
     8                 right = mid ;
     9             }
    10             //upper part: 这里没有 duplicate, 所以写 nums[mid] > nums[left] 一样通过
    11             else if(nums[mid]>nums[right]){
    12                 left = mid ;
    13             }
    14         }
    15         //post processing
    16         return Math.min(nums[left], nums[right]) ;
    17     }

    这个笨方法也能通过

     1 public int findMin(int[] nums) {
     2         if (nums ==null || nums.length ==0) return -1 ;
     3         int left = 0, right = nums.length -1 ;
     4         while(left + 1 < right){
     5             int mid = left +(right-left)/2 ;
     6             //this is the case for test case [1,2,3]: not necessary rotated
     7             if(nums[left] <= nums[mid] && nums[mid]<=nums[right]){
     8                 right = mid ;
     9             }
    10             else if (nums[mid] > nums[left] && nums[mid]>=nums[right]){
    11                 left = mid ;
    12             } else if(nums[mid]<=nums[left]){
    13                 right = mid ;
    14             }
    15         }
    16         //post processing
    17         return Math.min(nums[left], nums[right]) ;
    18     }
  • 相关阅读:
    bzoj 3993: [SDOI2015]星际战争
    bzoj 4066: 简单题
    bzoj 3611: [Heoi2014]大工程
    bzoj 3530: [Sdoi2014]数数
    bzoj 3529: [Sdoi2014]数表
    bzoj 3504: [Cqoi2014]危桥
    bzoj 3489: A simple rmq problem
    bzoj 3211: 花神游历各国
    bzoj 3196: Tyvj 1730 二逼平衡树
    bzoj 3172: [Tjoi2013]单词
  • 原文地址:https://www.cnblogs.com/davidnyc/p/8468908.html
Copyright © 2020-2023  润新知