题目来源【Leetcode】
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).
Example 1:
Input: [3, 2, 1]
Output: 1
Explanation: The third maximum is 1.Example 2:
Input: [1, 2]
Output: 2
Explanation: The third maximum does not exist, so the maximum (2) is returned instead.Example 3:
Input: [2, 2, 3, 1]
Output: 1
Explanation: Note that the third maximum here means the third maximum distinct number.
Both numbers with value 2 are both considered as second maximum.
这道题比较简单,就是求第三大的数,考虑好几种特殊情况就没啥问题了
class Solution {
public:
int thirdMax(vector<int>& nums) {
int s = nums.size();
if(s == 0) return 0;
sort(nums.begin(),nums.end());
nums.erase(unique(nums.begin(),nums.end()),nums.end());
if(nums.size() == 1) return nums[0];
else if(nums.size() == 2) return nums[1];
else if(nums.size() == 3) return nums[0];
else return nums[nums.size()-3];
}
};

本文介绍了一种在非空整数数组中寻找第三大数的算法,并提供了具体实现案例。当数组中不存在第三大数时,则返回最大数。文章通过排序和去重实现了O(n)的时间复杂度。
791

被折叠的 条评论
为什么被折叠?



