LeetCode 153. Find Minimum in Rotated Sorted Array(旋轉陣列查詢)
阿新 • • 發佈:2019-01-02
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.
You may assume no duplicate exists in the array.
方法一:遞迴+分治策略。
public class Solution { private int min(int[] nums, int from, int to) { if (from == to) return nums[from]; if (nums[from] < nums[to]) return nums[from]; int m = (from+to)/2; if (nums[m] > nums[to]) return min(nums, m + 1, to); return min(nums, from, m); } public int findMin(int[] nums) { return min(nums, 0, nums.length-1); } }
方法二:二分法。
public class Solution { public int findMin(int[] nums) { int from = 0, to = nums.length-1; while (nums[from]>nums[to]) { int mid = (from+to)/2; if (nums[mid] > nums[to]) from = mid + 1; else to = mid; } return nums[from]; } }