LeetCode No.414 Third Maximum Number | #Array #long_vs_int

Q:

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:
Input: [3, 2, 1]
Output: 1

Explanation: The third maximum is 1.
Example 2:
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.

A:

  1. Long.MIN_VALUE = -9223372036854775808 vs Integer.MIN_VALUE = -2147483648
    當test case = [1, 2, -2147483648]時,應該返回-2147483648,這個值是第三大。但如果代碼為return third == Integer.MIN_VALUE? first :third,那么判斷會成立而返回first值。因為當時初始化后,系統(tǒng)混淆了Integer.MIN_VALUE?和nums[2]的值。
  2. continue;只會結(jié)束current iteration,
    break;直接move forward to next code block了。
  3. 一直track,top3 最大值,每一次都要比較,只要出現(xiàn)不同,就要進行替換。
public class Solution {
    public int thirdMax (int[] nums) {
        long first = Long.MIN_VALUE;
        long second = Long.MIN_VALUE;
        long third = Long.MIN_VALUE;
        for (int i:nums){
            if (i>first){
                third = second;
                second = first;
                first = i;
            }else if (i == first)     //必要
                continue;
            else if (i > second){
                third = second;
                second = i;
            }else if (i == second)     //必要
                continue;
            else if (i > third){
                third = i;
            }
        }
        return third == Long.MIN_VALUE ? (int)first : (int)third;
          //method 要求返回類型為int,強制轉(zhuǎn)化一下,narrowing conversion
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容