題目:
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.
就是按順序排的數組,只不過這個順序的開頭可能不在數組開頭。所以當出現下一個比上一個小的時候,下一個就是最小的數。注意一點,當爲一個數的時候,可以和開頭爲最小合併。題目說不會有相等的存在,所以用小於等於做判斷,等於的話說明只有一個元素。那麼它本身爲最小。
代碼:
class Solution {
public:
int findMin(vector<int>& nums) {
if(nums[0] <= nums[nums.size()-1]){
return nums[0];
}
for(int i = 1; i < nums.size(); ++i){
if(nums[i] < nums[i-1]){
return nums[i];
}
}
}
};