lintcode160- Find Minimum in Rotated Sorted Array II- medium
阿新 • • 發佈:2017-09-23
art imu while img get solution star 比對 mat
Suppose a sorted array 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.
Notice
The array may contain duplicates.
ExampleGiven [4,4,5,6,7,0,1,2]
return 0
.
和I類似,OOXX二分法(find the first X),只是對比對象變掉。從原來的最後一個數,變為最後開始數起第一個比不等於nums[0]的數。
public class Solution { /* * @param nums: a rotated sorted array * @return: the minimum number in the array */ public int findMin(int[] nums) { //返回int這裏怎麽處理? if (nums == null || nums.length == 0){ throw new IllegalArgumentException(); }int start = 0; int end = nums.length - 1; while (end > 0 && nums[end] == nums[start]){ end--; } int cmpTarget = nums[end]; while (start + 1 < end){ int mid = start + (end - start) / 2; if (nums[mid] > cmpTarget){ start= mid; } else { end = mid; } } return Math.min(nums[start], nums[end]); } }
lintcode160- Find Minimum in Rotated Sorted Array II- medium