题目:
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.
题意:给定一个排好序并且做过旋转操作的数组(旋转点之前不知道),找到数组中最小的元素,假设数组中不存在重复元素。
思路:
观察例子中给定数组的最开始和最末尾元素,我们可以发现,如果第一个元素小于最后一个元素,则数组没有旋转,所以可以直接返回子串中的第一个元素。
如果第一个元素大于最后一个元素,我们计算该数组的中间值,并和第一个元素进行比较。
代码:6ms
class Solution { public: int findMin(vector<int>& nums) { int first = 0; int last = nums.size()-1; while(first<last){ if(nums[first]<nums[last]){ return nums[first]; } int mid = (first + last)/2; if(nums[first]<=nums[mid]){ first = mid + 1; }else{ last = mid; } } return nums[first]; } };代码:4ms 时间复杂度最低
class Solution { public: int findMin(vector<int>& nums) { int start = 0, end = nums.size()-1, mid; while (nums[start] > nums[end]) { mid = (start + end) / 2; if (nums[mid] > nums[start]) start = mid+1; else { ++start; end = mid; } } return nums[start]; } };