Description
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
Input: [3, 2, 1]
Output: 1
Explanation: The third maximum is 1.
Solution
|
|
Result
AC
Analyse
这个方法很简洁,因为要判断nums[i]和nums[i - 1]的大小比较,但是在i-1的过程中担心i-1会超过左边界,所以count开始就算1,这样相当于把最大的那个数在for之前已经算了。后来看了几个别的算法,觉得我的算法是最好的。
First
|
|
Analyse
这个算法就是利用了Integer的空属性,但是写的时候要注意用equals而不是==。
Second
|
|
Analyse
利用了PriorityQueue的默认排序是增序,再加上一个HashSet进行重复性的判断,有个地方需要注意的是如果queue的size大于3,那么set也要把这个对应的数字也remove。