【LeetCode】153. Find Minimum in Rotated Sorted Array (3 solutions)
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.
与Search in Rotated Sorted Array,Search in Rotated Sorted Array II,Find Minimum in Rotated Sorted Array II对照看
解法一:暴力解法,直接使用algorithm库中的求最小元素函数
需要遍历整个vector
class Solution { public: int findMin(vector<int> &num) { if(num.empty()) return 0; vector<int>::iterator iter = min_element(num.begin(), num.end()); return *iter; } };
解法二:利用sorted这个信息。如果平移过,则会出现一个gap,也就是从最大元素到最小元素的跳转。如果没有跳转,则说明没有平移。
比上个解法可以省掉不少时间,平均情况下不用遍历vector了。
class Solution { public: int findMin(vector<int> &num) { if(num.empty()) return 0; else if(num.size() == 1) return num[0]; else { for(vector<int>::size_type st = 1; st < num.size(); st ++) { if(num[st-1] > num[st]) return num[st]; } return num[0]; } } };
解法三:二分查找
与Search in Rotated Sorted Array对照来看
Search in Rotated Sorted Array题中是二分查找最大值,而本题是二分查找最小值。
class Solution { public: int findMin(vector<int>& nums) { if(nums.empty()) return 0; if(nums.size() == 1) return nums[0]; int n = nums.size(); int low = 0; int high = n-1; while(low < high && nums[low] > nums[high]) { int mid = low + (high-low)/2; if(nums[mid] < nums[low]) // mid is in second part high = mid; else if(nums[mid] == nums[low]) // since (low<high)-->(low+1==high) return nums[high]; // nums[low]>nums[high] else low = mid+1; } return nums[low]; } };