Third Maximum Number

来源:互联网 发布:淘宝卖家的基本义务 编辑:程序博客网 时间:2024/05/16 12:15

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: 1Explanation: The third maximum is 1.

Example 2:

Input: [1, 2]Output: 2Explanation: The third maximum does not exist, so the maximum (2) is returned instead.

Example 3:

Input: [2, 2, 3, 1]Output: 1Explanation: 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();    }


0 0