[抄題]:算法
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:ide
Input: [3, 2, 1] Output: 1 Explanation: The third maximum is 1.
Example 2:oop
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.
[暴力解法]:this
時間分析:nlgnspa
空間分析:debug
[優化後]:code
時間分析:nblog
空間分析:
[奇葩輸出條件]:
[奇葩corner case]:
[思惟問題]:
[一句話思路]:
不容許排序,就只能一個個地放了
[輸入量]:空: 正常狀況:特大:特小:程序裏處理到的特殊狀況:異常狀況(不合法不合理的輸入):
[畫圖]:
用else if :
[一刷]:
[二刷]:
[三刷]:
[四刷]:
[五刷]:
[五分鐘肉眼debug的結果]:
[總結]:
同時判斷要用else if
[複雜度]:Time complexity: O(n) Space complexity: O(1)
[英文數據結構或算法,爲何不用別的數據結構或算法]:
[關鍵模板化代碼]:
[其餘解法]:
[Follow Up]:
[LC給出的題目變變變]:
class Solution { public int thirdMax(int[] nums) { //ini Integer max1 = null; Integer max2 = null; Integer max3 = null; //for loop, change for (Integer n : nums) { if (n.equals(max1) || n.equals(max2) || n.equals(max3)) continue; if (max1 == null || n > max1) { max3 = max2; max2 = max1; max1 = n; } else if (max2 == null || n > max2) { max3 = max2; max2 = n; } else if (max3 == null || n > max3) { max3 = n; } } //return return (max3 == null) ? max1 : max3; } }
[代碼風格] :