LeetCode: Add to List 414. Third Maximum Number

30 篇文章 0 订阅
21 篇文章 0 订阅

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.

题意:题目要求输出严格第三大的数,如果没有,则输出最大数。并且要求时间复杂度为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;
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值