Description:
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.
随机找一个枢纽,旋转有序数组,找出最小元素。
O(n)解法,线性查找。1ms
public class Solution { public int findMin(int[] nums) { int min = nums[0]; for(int i=1; i<nums.length; i++) { if(min > nums[i]) min = nums[i]; } return min; } }
O(logn)解法,二分。0ms
public class Solution { public int findMin(int[] nums) { int n = nums.length - 1; int left = 0, right = nums.length - 1; while(left <= right) { int mid = left + (right - left) / 2; if(nums[mid] > nums[n]) { left = mid + 1; } else { right = mid - 1; } } return nums[left]; } }