?LeetCode刷題實戰(zhàn)414:第三大的數(shù)
Given an integer array nums, return the third distinct maximum number in this array. If the third maximum does not exist, return the maximum number.
示例
示例 1:
輸入:[3, 2, 1]
輸出:1
解釋:第三大的數(shù)是 1 。
示例 2:
輸入:[1, 2]
輸出:2
解釋:第三大的數(shù)不存在, 所以返回最大的數(shù) 2 。
示例 3:
輸入:[2, 2, 3, 1]
輸出:1
解釋:注意,要求返回第三大的數(shù),是指在所有不同數(shù)字中排第三大的數(shù)。
此例中存在兩個值為 2 的數(shù),它們都排第二。在所有不同數(shù)字中排第三大的數(shù)為 1 。
解題
我們可以利用TreeSet 。把元素都插入TreeSet里面,會自動升序排列 。
在插入過程中,一直維護一個長度為3的,如果大于3,那么刪除最小的那個
插入完畢
沒有第三個 就返回最后一個(最大值) ,否則返回第一個
class?Solution?{
????public?int?thirdMax(int[] nums) {
????????TreeSetset=new?TreeSet();
????????for(int?i:nums){
????????????set.add(i);
????????????if(set.size()>3){
?????????????????set.pollFirst();
????????????}
????????}
????????if(set.size()<3){
????????????return?set.pollLast();
????????}else{
????????????return?set.pollFirst();
????????}
????}
}
LeetCode刷題實戰(zhàn)402:移掉 K 位數(shù)字
LeetCode刷題實戰(zhàn)405:數(shù)字轉(zhuǎn)換為十六進制數(shù)
LeetCode刷題實戰(zhàn)406:根據(jù)身高重建隊列
LeetCode刷題實戰(zhàn)410:分割數(shù)組的最大值
LeetCode刷題實戰(zhàn)411:最短獨占單詞縮寫
LeetCode刷題實戰(zhàn)412:Fizz Buzz
