标签:
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.
求一个已经排好序的数组旋转之后的最小值,且该数组中无重复元素。因为是按升序排好序的数组旋转,则旋转之后新数组为 升序----突然变小-----升序。则我们找到突然变小的那个数字即可,那就是最小值,代码如下:
class Solution { public: int findMin(vector<int>& nums) { if(nums.size()==1) return nums[0]; if(nums.size()==2) { return min(nums[0],nums[1]); } int min=nums[0]; for(int i=0;i<nums.size()-1;i++) { if(nums[i]>nums[i+1]) min=nums[i+1]; } return min; } };
class Solution { public: int findMin(vector<int>& nums) { if(nums.size()==1) return nums[0]; if(nums.size()==2) return min(nums[0],nums[1]); for(int i=0;i<nums.size()-1;i++) { if(nums[i+1]<nums[i]) return nums[i+1]; } return nums[0]; } };
class Solution { public: int findMin(vector<int>& nums) { if(nums.size()==0) return 0; int low=0,high=nums.size()-1; while(low<high) { int mid=(low+high)/2; if(nums[mid]>nums[high]) low=mid+1; else if(nums[mid]<nums[high]) high=mid; else { if(nums[mid]==nums[low]) { low++; high--; } else high--; } } return nums[high]; } };
Find Minimum in Rotated Sorted Array I II
标签:
原文地址:http://blog.csdn.net/sinat_24520925/article/details/46438537