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.
这道题的测试用例有MIN_VALUE 这个值,因此如果想用三个变量保存前三大的值的话,这三个变量得是long型的,有点蛋疼;于是用priorityqueue做可以避免这些事情;但是这道题是不允许重复的,所以要用一个set保存结果。这样扫一遍就知道第三大是少多了。如果不存在第三大,那么要么是1 要么是2, 2的话再删除一个元素,返回最大值。
代码:
public int thirdMax(int[] nums) {
Queue<Integer> queue = new PriorityQueue<>();
Set<Integer> set = new HashSet<>();
for(int num: nums){
if(!set.contains(num)){
set.add(num);
queue.offer(num);
if(queue.size()>3) queue.poll();
}
}
if(queue.size()==2) queue.poll();
return queue.peek();
}