码迷,mamicode.com
首页 > 其他好文 > 详细

LC.153.Find Minimum in Rotated Sorted Array

时间:2018-02-25 13:12:08      阅读:138      评论:0      收藏:0      [点我收藏+]

标签:最小   sts   size   find   desc   ini   ems   for   first   

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             if (nums[mid] < nums[right]){
 7                 right = mid ;
 8             } else{
 9                 //first half: left = mid, move to right
10                 left = mid ;
11             }
12         }
13         return nums[left]<nums[right]? nums[left] : nums[right] ;
14     }

 

LC.153.Find Minimum in Rotated Sorted Array

标签:最小   sts   size   find   desc   ini   ems   for   first   

原文地址:https://www.cnblogs.com/davidnyc/p/8468908.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!