LeetCode Find Minimum in Rotated Sorted Array

來源:互聯網
上載者:User

標籤:

原題連結在這裡: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 218         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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.