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:

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.

这题的思路是用三个变量保存前三大的数字。三个变量的初始值都是Long.Min_Value,因为测试用例会包括一个-2^31方的值,这个值已经超过interger的范围。

用一个循环更新记录。先跟最大值比较,如果大鱼它则依次更新;如果等于它,那么continue;以此类推。

按照题目要求如果没有第三大的值,直接返回最大值。

public int thirdMax(int[] nums) {
        if(nums == null || nums.length == 0) return 0;
        //要考虑不存在的情况

        long f = Long.MIN_VALUE;
        long s = Long.MIN_VALUE;
        long t = Long.MIN_VALUE;
        for(int i=0;i<nums.length;i++){
            if(nums[i]>f){
                t = s;
                s = f;
                f = nums[i];
            }else if(nums[i] == f){
                continue;
            }else if(nums[i]>s){
                t = s;
                s = nums[i];
            }else  if(nums[i] == s){
                continue;
            }
            else if(nums[i]>=t){
                t = nums[i];
            }else if(nums[i] == t){
                continue;
            }
        }
        if(t!= Long.MIN_VALUE){
            return (int)t;
        }else{
            return (int)f;
        }
    }

------------ 1.4.2017

更新

还有就是用priority queue来做,就没那么麻烦的

代码:

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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值