Given a non-empty array of integers, return the third maximum number in this array. If it does not exist, return the maximum number. The time complexity must be in O(n).
思路:由于复杂度限制在O(n),直接遍历寻找最大值,再依次找第二大,第三大的需要三个循环,比较麻烦。我们先将原数组进行由小到大排序,然后直接从末尾开始找到第三大的数,排序为O(logn),查找只需一次循环,最坏情况刚好O(n).
class Solution {
public:
int thirdMax(vector<int>& nums) {
sort(nums.begin(), nums.end());
int result = nums[nums.size() - 1];
int num = 1;
for (int i = nums.size() - 2; i >=0; i--) {
if (nums[i] < result) {
num++;
result = nums[i];
if (num == 3) {
return result;
}
}
}
return nums[nums.size() - 1];
}
};