Add Date 2014-10-15數組
Find Minimum in Rotated Sorted Arrayspa
Suppose a sorted array is rotated at some pivot unknown to you beforehand.code
(i.e., 0 1 2 4 5 6 7
might become 4 5 6 7 0 1 2
).blog
Find the minimum element.element
You may assume no duplicate exists in the array.leetcode
這個很簡單,由於沒有重複數字,數組本質上仍是有序的,用相似二分查找的方法複雜度O(log n)。記得考慮一下整個數組沒有 rotated 的狀況。get
20號又加了有重複數字的題II,直接附II的 code 吧,II中須要考慮前中後三個數相等的狀況,此時沒法肯定最小值在哪邊,只能遍歷一遍。io
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 };