LeetCode/solutions/414. Third Maximum Number.md
2019-09-13 23:08:41 +08:00

28 lines
1.1 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# [414. Third Maximum Number](https://leetcode.com/problems/third-maximum-number/description/)
# 思路
题意就是找出数组第三大的数注意相同的数算作一个数可以考虑遍历三次第一次得到最大的数max1第二次得到第二大的数max2第三次就得到了第三大的数max3。
注意可以用INT_MIN(在limits.h里)表示int型最小的数另外需要用一个tag记录是否找到max3否则当max3==INT_MIN时无法判断max3是否是真的第三大的值还是初始值。
# C++
```C++
class Solution {
public:
int thirdMax(vector<int>& nums) {
int max1 = INT_MIN, max2 = INT_MIN, max3 = INT_MIN, tag = 0;
for(int num: nums)
if(max1 <= num)
max1 = num;
for(int num: nums)
if(max2 <= num && num != max1)
max2 = num;
for(int num: nums)
if(max3 <= num && num != max1 && num != max2){
max3 = num;
tag = 1;
}
if(tag == 0) return max1;
return max3;
}
};
```