leetCode練習(153)、(154)
阿新 • • 發佈:2019-01-02
題目:Find Minimum in Rotated Sorted Array
難度:medium
問題描述:
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.
Example 1:
Input: [3,4,5,1,2] Output:1
Example 2:
Input: [4,5,6,7,0,1,2] Output: 0
解題思路:
兩點法即可,不過要考慮沒有摺疊時的特殊情況。154在於可能有重複元素。
程式碼如下:
public static int findMin(int[] nums) { int len = nums.length; if(nums.length == 1) return nums[0]; int p1 = 0,p2 = len-1; if(nums[len-1]>nums[0]) return nums[0]; while(true){ if(p1>=p2-1) return Math.min(nums[p1], nums[p2]); int mid = (p1+p2)>>1; //System.out.println(mid); if(nums[mid]>=nums[p1]){ //mid在前半段 p1 = mid; continue; }else{ //mid在後半段 p2 = mid; continue; } } }
154程式碼如下:
public int findMin2(int[] nums) { int len = nums.length; if(nums.length == 1) return nums[0]; int p1 = 0,p2 = len-1,mid = 0; if(nums[len-1]>nums[0]) return nums[0]; while(p1<p2){ //3,4,5,1,2 --情形1 //1,2,3,4,5 --情形2 mid = (p1+p2)>>1; if(nums[mid]>nums[p2]){//只存在於情形1 p1 = mid+1; }else if(nums[mid]<nums[p2]){//情形1和2都有 p2 = mid; }else{//nums[mid]==nums[p2],p2即使是最小值也不影響 p2 = p2-1; } } return nums[p1]; }