[leetcode]414. Third Maximum Number
Analysis
everyday is the first day of your rest life—— [间歇性迷茫~]
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).
给定一个数组,找到数组中第三大的数,如果没有第三大的数,则输出第二大的数,以此类推。需要注意的是,数组中可能有重复的数字,所以先用set去重,然后排一下序就行了。
Implement
class Solution {
public:
int thirdMax(vector<int>& nums) {
set<int> num(nums.begin(), nums.end());
set<int>::iterator it;
vector<int> res;
int tmp;
for(it=num.begin(); it!=num.end(); it++){
tmp = *it;
res.push_back(tmp);
}
sort(res.begin(), res.end());
int len = res.size();
if(len<3)
return res[len-1];
else
return res[len-3];
}
};
下面是discussion里面一个大佬的解
int thirdMax(vector<int>& nums) {
long long a, b, c;
a = b = c = LLONG_MIN;
for (auto num : nums) {
if (num <= c || num == b || num == a) continue;
c = num;
if (c > b) swap(b, c);
if (b > a) swap(a, b);
}
return c == LLONG_MIN ? a : c;
}