---
# System prepended metadata

title: \#414 Third Maximum Number
tags: [leetcode, leetcode-easy]

---

# \#414 Third Maximum Number
## *給定一數字陣列, 回傳第三大數字, 如果沒有則回傳最大數字*
## Log
 - build 20210812 by syhuang

## 另解
 - 三變數記錄前三大數字, 比較慢
 - leetcode submit runtime 10%, memory 70%
```javascript=
var thirdMax = function(nums) {
    let t_1st, t_2nd, t_3rd;
    for(const n of nums){
        if(n==t_1st || n==t_2nd || n==t_3rd) continue;
        if(typeof(t_1st)=='undefined' || t_1st<n){
            t_3rd = t_2nd;
            t_2nd = t_1st;
            t_1st = n;
        }else if(typeof(t_2nd)=='undefined' || t_2nd<n){
            t_3rd = t_2nd;
            t_2nd = n;
        }else if(typeof(t_3rd)=='undefined' || t_3rd<n) t_3rd = n;
    }
    return typeof(t_3rd)!='undefined'?t_3rd:t_1st;
};
```
## 初見
 - 轉成set把數字唯一化->排序->回傳3rd
 - leetcode submit runtime 30%, memory 80%
```javascript=
var thirdMax = function(nums) {
    let a = Array.from(new Set(nums)).sort(function(a,b){return b-a});
    return a.length>2?a[2]:a[0];
};
```
## 備註
- [參考解](https://leetcode.com/problems/third-maximum-number/discuss/90202/Java-neat-and-easy-understand-solution-O(n)-time-O(1)-space)
## 參考
###### tags: `leetcode`, `leetcode-easy`