Third Maximum Number:找第三大的数

该博客介绍了一个问题,即在给定的非空整数数组中找到第三大的数。如果不存在,则返回最大数。解决方案是使用一个大小为3的优先队列,以O(N)的时间复杂度和常数级别的空间复杂度实现。博客提到了三个示例来说明问题。
摘要由CSDN通过智能技术生成

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();
    }
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值