LeetCode: Add to List 414. Third Maximum Number

来源:互联网 发布:linux服务器系统占有率 编辑:程序博客网 时间:2024/06/16 10:21

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.

题意:题目要求输出严格第三大的数,如果没有,则输出最大数。并且要求时间复杂度为O(n)。
分析:
1、严格第三大的数,则冒泡排序并不能确定外循环的次数。所以不能直接使用。
2、严格第三大的数,可以去除重复数据,java中hashset是利用hash函数实现的去重,符合O(n)的要求,然后再进行冒泡排序。
3、看到网络上的记录三个数,扫描一遍数组的算法,其中需要注意点是:数组中可能存在Integer.MIN_VALUE,所以在初始化三个数时需要初始化一个更小的数。另外需要判断如何确定是否存在严格第三大的数。
代码实现的是记录三个数的算法,如下:

class Solution {    public int thirdMax(int[] nums) {        if(nums==null||nums.length==0)            return 0;        long first=Long.MIN_VALUE;        long second=first;        long third=first;        int n=nums.length;        for(int i=0;i<n;i++){            if(nums[i]>first)            {                third=second;                second=first;                first=nums[i];            }                else if(nums[i]<first&&nums[i]>second)            {                third=second;                second=nums[i];            }               else if(nums[i]<second&&nums[i]>third)                third=nums[i];        }        return (third==Long.MIN_VALUE||third==second)? (int)first:(int)third;    }}