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值。因為當時初始化后,系統混淆了Integer.MIN_VALUE?和nums[2]的值。
  2. continue;只會結束current iteration,
    break;直接move forward to next code block了。
  3. 一直track,top3 最大值,每一次都要比較,只要出現不同,就要進行替換。
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,強制轉化一下,narrowing conversion
    }
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容