LeetCode 414. 第三大的数

题目链接:

力扣icon-default.png?t=M1L8https://leetcode-cn.com/problems/third-maximum-number/

【方法一】直接去重后排序,选第三小的值出来

class Solution {
    public int thirdMax(int[] nums) {
        Set<Integer> set = new HashSet<Integer>();
        int n = nums.length;
        for (int i = 0; i < n; i ++) set.add(nums[i]);
        Object[] tmp = set.toArray();
        Arrays.sort(tmp);
        n = tmp.length;
        if(n < 3) return (int) tmp[n - 1];
        return (int)tmp[n - 3];
    }
}

 【方法二】三个变量a,b,c分别记录前三大的数。

class Solution {
    public int thirdMax(int[] nums) {
        long a = (long)Integer.MIN_VALUE - 1, b = (long)Integer.MIN_VALUE - 1, c = (long)Integer.MIN_VALUE - 1;
        int n = nums.length, i, flag = 0;
        for(i = 0; i < n; i++){
            if(nums[i] > a){
                c = b; b = a; a = nums[i]; 
            }else if(nums[i] < a && nums[i] > b){
                c = b; b = nums[i];
            }else if(nums[i] < b && nums[i] > c){
                c = nums[i]; flag = 1;
            }
        }
        return c == (long)Integer.MIN_VALUE - 1? (int)a: (int)c;
    }
}

【方法三】使用java的TreeSet

class Solution {
    public int thirdMax(int[] nums) {

        TreeSet<Integer> set = new TreeSet<>();
        for(Integer it: nums){
            set.add(it);
            if(set.size() > 3) set.remove(set.first());
        }
        return set.size() == 3 ? set.first(): set.last();
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值