【LeetCode】Find Minimum in Rotated Sorted Array 在旋转数组中找最小数
Add Date 2014-10-15
Find Minimum in Rotated Sorted Array
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(log n)。记得考虑一下整个数组没有 rotated 的情况。
20号又加了有重复数字的题II,直接附II的 code 吧,II中需要考虑前中后三个数相等的情况,此时无法确定最小值在哪边,只能遍历一遍。
1 class Solution { 2 public: 3 int findMinN(vector<int> &num, int min, int max) { 4 int minN = num[min]; 5 for(int i = min+1; i <= max; ++i) { 6 if(num[i] < minN) 7 minN = num[i]; 8 } 9 return minN; 10 } 11 int findMin(vector<int> &num, int min, int max) { 12 if(min == max || num[min] < num[max]) 13 return num[min]; 14 int mid = (max+min)>>1; 15 if(num[mid] < num[min]) { 16 return findMin(num, min, mid); 17 } 18 else if(num[mid] > num[max]) { 19 return findMin(num, mid+1, max); 20 } 21 else 22 return findMinN(num, min, max); 23 } 24 int findMin(vector<int> &num) { 25 int len = num.size(); 26 return findMin(num, 0, len-1); 27 } 28 };