标签:
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.
Subscribe to see which companies asked this question
//思路首先:遍历一遍时间复杂度是O(N) class Solution { public: int findMin(vector<int>& nums) { int minum=nums[0]; for(int i=1;i<nums.size();i++) { if(nums[i]<minum) minum=nums[i]; } return minum; } };
//思路首先:第二种方法还是直接遍历, //按照题目所说数组应该是先上升,在下降,如果下降了,这个值就是最小值 class Solution { public: int findMin(vector<int>& nums) { int minum=nums[0]; for(int i=1;i<nums.size();i++) { if(nums[i-1]>nums[i]) { minum=nums[i]; break; } } return minum; } };
//思路首先:第三种方法,二分法 // class Solution { public: int findMin(vector<int>& nums) { if(nums.empty()) return 0; if(nums.size() == 1) return nums[0]; int low = 0, high = nums.size()-1; while(low < high && nums[low] > nums[high]) { int mid = low + (high-low)/2; if(nums[mid] < nums[low]) high = mid; else if(nums[mid] == nums[low]) return nums[high]; else low = mid+1; } return nums[low]; } };
<LeetCode OJ> Find Minimum in Rotated Sorted Array【153】
标签:
原文地址:http://blog.csdn.net/ebowtang/article/details/50424986