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.

 [暴力解法]:

时间分析:nlgn

空间分析:

 [优化后]:

时间分析:n

空间分析:

[奇葩输出条件]:

[奇葩corner case]:

[思维问题]:

[一句话思路]:

不允许排序,就只能一个个地放了

[输入量]:空: 正常情况:特大:特小:程序里处理到的特殊情况:异常情况(不合法不合理的输入):

[画图]:

else if :

[一刷]:

  1. 去重复的方法:用continue继续处理,好像很少用。

[二刷]:

[三刷]:

[四刷]:

[五刷]:

  [五分钟肉眼debug的结果]:

[总结]:

同时判断要用else if 

[复杂度]:Time complexity: O(n) Space complexity: O(1)

[英文数据结构或算法,为什么不用别的数据结构或算法]:

  1. 不能初始化为0,就包装一下,初始化为null
  2. 或者初始化为极值

[关键模板化代码]:

[其他解法]:

[Follow Up]:

[LC给出的题目变变变]:

class Solution {
    public int thirdMax(int[] nums) {   
        //ini
        Integer max1 = null;
        Integer max2 = null;
        Integer max3 = null;
        
        //for loop, change
        for (Integer n : nums) {
            if (n.equals(max1) || n.equals(max2) || n.equals(max3)) continue;
            if (max1 == null || n > max1) {
                max3 = max2;
                max2 = max1;
                max1 = n;
            }
            else if (max2 == null || n > max2) {
                max3 = max2;
                max2 = n;
            }
            else if (max3 == null || n > max3) {
                max3 = n;
            }
        }
        
        //return
        return (max3 == null) ? max1 : max3;
    }
}
View Code

 

 [代码风格] :

posted @ 2018-04-21 21:29  苗妙苗  阅读(617)  评论(0编辑  收藏  举报