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

LeetCode Find Minimum in Rotated Sorted Array

时间:2015-10-05 06:58:51      阅读:173      评论:0      收藏:0      [点我收藏+]

标签:

原题链接在这里:https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/

Method 1 就是找到第一个违反升序的值,就是最小值,若是没有,那么第一个值就是最小值. Time O(n).

但还有更快的方法,比O(n)更快的方法就是O(log n), 使用Binary Search 查找.

e.g. 4,5,6,7,0,1,2 若是有了rotatation, nums[left] 是会大于nums[right]的,根据此法使用Binary Search.

nums[mid]  = 7, nums[left] = 4, nums[left] < nums[mid], 能看出0在nums[mid]的右侧,就在右侧继续找, left = mid-1. 反之就在左侧找.

Note:

1. 若是nums[left] == nums[right] 时,left++,  避免陷入infinite loop.

2. while loop 的条件是 left < right-1. 注意减一。e.g. 若是没有减一 [3,4,5,1,2], left = 0, right = 4, mid = 2, res = nums[0] = 3;

left = mid+1 后 left =3 < right, mid = 3, left++, left == right 跳出loop. 此时 比较 res 和 nums[left], nums[right], res = 2. 丢掉了 1.

3. 用这种方法时需要最后再取res = Math.min(res, nums[l])和res = Math.min(res, nums[r]). e.g. [2,1], left = 0, right = 1, mid = 0. nums[left] == nums[mid], left++.

left = 1, right = 1,  跳出 loop, 但是此时的res 还是 nums[0]=2. 没有更新到 nums[1].

AC Java:

 

 1 public class Solution {
 2     public int findMin(int[] nums) {
 3         /*
 4         //Mehtod 1
 5         if(nums == null || nums.length == 0){
 6             return Integer.MAX_VALUE;
 7         }
 8         int res = nums[0];
 9         for(int i = 1; i<nums.length; i++){
10             if(nums[i]<nums[i-1]){
11                 res = nums[i];
12             }
13         }
14         return res;
15         */
16         
17         //Method 2
18         if(nums == null || nums.length == 0){
19             return Integer.MAX_VALUE;
20         }
21         int l = 0;
22         int r = nums.length - 1;
23         int res = nums[0];
24         while(l<r-1){
25             int mid = l+(r-l)/2;
26             if(nums[l] < nums[mid]){
27                 res = Math.min(res, nums[l]);
28                 l = mid+1;
29             }else if(nums[l] > nums[mid]){
30                 res = Math.min(res, nums[mid]);
31                 r = mid-1;
32             }else{
33                 l++;
34             }
35         }
36         res = Math.min(res, nums[l]);
37         res = Math.min(res, nums[r]);
38         return res;
39     }
40 }

 

LeetCode Find Minimum in Rotated Sorted Array

标签:

原文地址:http://www.cnblogs.com/Dylan-Java-NYC/p/4855292.html

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