leetcode|第三大的数java题解

由于在面试作业帮、好未来侧开实习面试的时候都被问到了这道题,所以我就来写个题解吧

给你一个非空数组,返回此数组中 第三大的数 。如果不存在,则返回数组中最大的数。

示例 1:

输入:[3, 2, 1] 输出:1 解释:第三大的数是 1 。 示例 2:

输入:[1, 2] 输出:2 解释:第三大的数不存在, 所以返回最大的数 2 。 示例 3:

输入:[2, 2, 3, 1] 输出:1 解释:注意,要求返回第三大的数,是指在所有不同数字中排第三大的数。 此例中存在两个值为 2
的数,它们都排第二。在所有不同数字中排第三大的数为 1 。

提示:

1 <= nums.length <= 104
-2 ^ 31 <= nums[i] <= 2 ^ 31 - 1

进阶:你能设计一个时间复杂度 O(n) 的解决方案吗?

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/third-maximum-number
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

分析此题:找第三大的数
分为两种情况:
存在第三大的数,返回第三大的数;
不存在第三大的数,返回第一大的数;不存在的情况主要是,数组长度小于等于2和数组去重元素之后长度小于等于2;

题解一:
设置max1,max2,max3为null,主要是为了好判断是否被赋值,通过遍历一次数组实现O(n)的时间复杂度。

使用Integer的原因是Integer的最大值和最小值刚好满足题目数据的要求。

 public int thirdMax(int[] nums) {
        Integer max1 = null, max2 = null,max3 = null;
        for (int i = 0 ;i < nums.length;i++){
            Integer cur = nums[i];

            if (cur.equals(max1) || cur.equals(max2) || cur.equals(max3))
                continue;  //遇到重复元素的情况下
            if (max1 == null || cur > max1){
                max3 = max2;
                max2 = max1;
                max1 = cur;
            }else if (max2 == null || cur > max2){
                max3 = max2;
                max2 = cur;
            }else if (max3 == null || cur > max3){
                max3 = cur;
            }
        }
        return max3 == null ? max1 : max3;

    }

题解二:
使用到了java中的数组排序和List集合,将数组排序后加入到list中,并且进行去重。此时就可以直接通过判断list的size进行判断是否存在第三大的数。

 public int thirdMax(int[] nums) {
        Arrays.sort(nums);
        List<Integer> ans = new ArrayList<>();

        for(int i:nums){
            if(ans.contains(i)){
                continue;
            }
            ans.add(i);
        }

        int n = ans.size();
        if(n==1 || n==2){
            return ans.get(n-1);
        }

        return ans.get(ans.size()-3);
    }

题解三:
这里使用到了Long,因为Long的最小值是-2^63 ,最大值是2^63 -1,使用Long不需要对最小值-2^31进行判断。

public int thirdMax(int[] nums) {
            long max1 = Long.MIN_VALUE, max2 = Long.MIN_VALUE, max3 = Long.MIN_VALUE;
            for (int num : nums) {
                if (num == max1 || num == max2 || num == max3) continue;
                if (num > max1) {
                    max3 = max2;
                    max2 = max1;
                    max1 = num;
                } else if (num > max2) {
                    max3 = max2;
                    max2 = num;
                } else if (num > max3) {
                    max3 = num;
                }
            }
            return (int) (max3 == Long.MIN_VALUE ? max1 : max3);
        }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值