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:ide

Input: [3, 2, 1]

Output: 1

Explanation: The third maximum is 1.

 

Example 2:oop

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.

 [暴力解法]:this

时间分析:nlgnspa

空间分析:debug

 [优化后]:code

时间分析:nblog

空间分析:

[奇葩输出条件]:

[奇葩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

 

 [代码风格] :

相关文章
相关标签/搜索