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.

讀題

這個題目的意思就是選出一個數組中第三大的數,需要注意的是相同的數字只算做一次

思路

非常暴力的做法就是先去重使用set,然后遍歷篩選過后的數組找到第三大的數,如果這個篩選的數組元素的個數小于等于2就直接返回最大的數

題解

public class Solution414 {
    public static int thirdMax(int[] nums) {
        Set set = new HashSet<Integer>();
        for (int i = 0; i < nums.length; i++) {
            set.add(nums[i]);
        }
        List<Integer> list = new ArrayList<Integer>(set);
        if (list.size() == 1)
            return list.get(0);
        if (list.size() == 2)
            return list.get(0) > list.get(1) ? list.get(0) : list.get(1);
        int a = list.get(0);
        int b = list.get(0);
        int c = list.get(0);
        for (int i = 1; i < list.size(); i++) {
            if (list.get(i) > b) {
                if (list.get(i) > a) {
                    c = b;
                    b = a;
                    a = list.get(i);
                }
                if (list.get(i) < a) {
                    c = b;
                    b = list.get(i);
                }
            }
            if (list.get(i) < b) {
                if (list.get(i) > c)
                    c = list.get(i);
            }
        }
        return c;
    }

    public static void main(String[] args) {
        int[] arr = new int[] {1,2,3};
        int result = Solution414.thirdMax(arr);
        System.out.println(result);
        // System.out.println(Integer.MIN_VALUE);
    }
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容