(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.
1 2 3 4 5 6 7 8 9 10 11 | class Solution { public: int findMin(vector<int>& nums) { int size=nums.size(); int min=nums[0]; for(int i=1;i<size;i++){ if(nums[i]<nums[i-1])return nums[i]; } return min; } }; |
-----------------------
或是BTS
比較快
1 2 3 4 5 6 7 8 9 10 11 | class Solution { public: int findMin(vector<int>& nums) { int l=0,r=nums.size()-1; while(l<r){ int mid = l + (r-l)/2; nums[mid]>nums[r] ? l=mid+1:r=mid; } return nums[l]; } }; |
沒有留言:
張貼留言