标签:
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.
The array may contain duplicates.
与Leetcode Find Minimum in Rotated Sorted Array 的区别只是有重复数字。
方法一:推荐用binary search. O(logn)
当A[mid] = A[end]时,无法判断min究竟在左边还是右边。
public class Solution { public int findMin(int[] nums) { int left = 0, right = nums.length-1; while(left < right) { int mid = left + (right - left) / 2; if(nums[mid] < nums[right]){ right = mid; }else if(nums[mid] > nums[right]){ left = mid+1; }else { right--; } } return nums[left]; } }
2.
public class Solution { public int findMin(int[] nums) { for(int i = 1; i < nums.length; i++){ if(nums[i] < nums[i-1]){ return nums[i]; } } return nums[0]; } }
Reference:
1. http://bangbingsyb.blogspot.com/2014/11/leecode-find-minimum-in-rotated-sorted.html
Leetcode Find Minimum in Rotated Sorted Array II
标签:
原文地址:http://www.cnblogs.com/anne-vista/p/4899736.html