LeetCode: Add to List 414. Third Maximum Number

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.

題意:題目要求輸出嚴格第三大的數,如果沒有,則輸出最大數。並且要求時間複雜度爲O(n)。
分析:
1、嚴格第三大的數,則冒泡排序並不能確定外循環的次數。所以不能直接使用。
2、嚴格第三大的數,可以去除重複數據,java中hashset是利用hash函數實現的去重,符合O(n)的要求,然後再進行冒泡排序。
3、看到網絡上的記錄三個數,掃描一遍數組的算法,其中需要注意點是:數組中可能存在Integer.MIN_VALUE,所以在初始化三個數時需要初始化一個更小的數。另外需要判斷如何確定是否存在嚴格第三大的數。
代碼實現的是記錄三個數的算法,如下:

class Solution {
    public int thirdMax(int[] nums) {
        if(nums==null||nums.length==0)
            return 0;
        long first=Long.MIN_VALUE;
        long second=first;
        long third=first;
        int n=nums.length;
        for(int i=0;i<n;i++){
            if(nums[i]>first)
            {
                third=second;
                second=first;
                first=nums[i];
            }    
            else if(nums[i]<first&&nums[i]>second)
            {
                third=second;
                second=nums[i];
            }   
            else if(nums[i]<second&&nums[i]>third)
                third=nums[i];
        }
        return (third==Long.MIN_VALUE||third==second)? (int)first:(int)third;
    }

}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章