标签:
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.
Given [4, 5, 6, 7, 0, 1, 2]
return 0.
分析:
这题明显要求用binary search, 但是当你用binary search的时候,你会发现余下的一半可能是单调递增的了,或者只剩下两个数,但是我们怎么判断那个pivot在哪里呢?我们需要先要处理以下两种special cases,处理好了就可以了。
1.单调递增
2. pivot是最后一个数。
1 public class Solution { 2 /** 3 * @param num: a rotated sorted array 4 * @return: the minimum number in the array 5 * cnblogs.com/beiyeqingteng/ 6 */ 7 public int findMin(int[] num) { 8 if (num == null || num.length == 0) return -1; 9 if (num.length == 1) return num[0]; 10 11 int start = 0; 12 int end = num.length - 1; 13 14 while (start < end) { 15 if (num[start] < num[end]) return num[start]; // handle case 1 16 if (num[end] < num[end - 1]) return num[end]; // handle case 2 17 18 int mid = start + (end - start) / 2; 19 if (num[mid - 1] > num[mid] && num[mid] < num[mid + 1]) { 20 return num[mid]; 21 } else if (num[start] < num[mid]){ 22 start = mid + 1; 23 } else { 24 end = mid - 1; 25 } 26 } 27 return -1; 28 } 29 }
转载请注明出处:cnblogs.com/beiyeqingteng/
Find Minimum in Rotated Sorted Array
标签:
原文地址:http://www.cnblogs.com/beiyeqingteng/p/5631746.html