#Leetcode# 153. Find Minimum in Rotated Sorted Array
阿新 • • 發佈:2018-11-28
exists num duplicate empty amp break NPU 一個 play
https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/
Suppose an array sorted in ascending order 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.
Example 1:
Input: [3,4,5,1,2] Output: 1
Example 2:
Input: [4,5,6,7,0,1,2] Output: 0
代碼1:
class Solution { public: int findMin(vector<int>& nums) { if(nums.empty()) return 0; int n = nums.size(); sort(nums.begin(), nums.end()); return nums[0]; } };View Code
代碼2:
class Solution { public:View Codeint findMin(vector<int>& nums) { if(nums.empty()) return 0; if(nums.size() == 1) return nums[0]; int n = nums.size(); int ans = nums[0]; for(int i = 0; i <= n - 2; i ++) { if(nums[i + 1] < nums[i]) { ans = nums[i + 1];break; } } return ans; } };
第一份代碼直接用 $sort$ 排序 才超過 $44%$ 左右 然後又寫了一個正解 寫第二份代碼的時候差一個等號改了半天 果然遊泳完腦子會進水的呢
#Leetcode# 153. Find Minimum in Rotated Sorted Array