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.
思路:找第三大的数,那就维持一个大小为3的优先队列,因为最坏情况下每个数字都需要比较三次,所以时间复杂度是O(3N)即O(N),空间复杂度为常数。
过完年了,继续做做题。
class Solution {
public int thirdMax(int[] nums) {
PriorityQueue<Integer> queue = new PriorityQueue<Integer>();
Set<Integer> set = new HashSet<Integer>();
for(Integer i:nums){
if(!queue.contains(i)){
queue.add(i);
set.add(i);
if(queue.size()>3){
int x = queue.poll();
set.remove(x);
}
}
}
if(queue.size()<3){
while(queue.size()>1) queue.poll();
}
return queue.peek();
}
}