Java-第三大的数(力扣)

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

示例 1:

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

示例 2:

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

示例 3:

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

我用的小根堆,最后败给了用例[1,2,-2147483648](无语)

下面是我的错误示范: 

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

        Arrays.sort(nums);
        int n=nums.length;
        int temp[]=new int[n];
        int p=0;
        for(int i=0;i<n;i++){
            if(i>0&&nums[i]==nums[i-1]){
                continue;
            }
            temp[p++]=nums[i];
        }
        if(p<3){
            int res[]=Arrays.copyOfRange(temp,0,p);
            Arrays.sort(res);
            return res[res.length-1];
        }

        PriorityQueue<Integer> priorityQueue=new PriorityQueue<>(new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                return o1-o2;
            }
        });
        for(int i=0;i<p;i++){
            if(i>0&&temp[i]==temp[i-1]){
                continue;
            }
            if(priorityQueue.size()<3){
                priorityQueue.add(temp[i]);
            }else{
                if(temp[i]>priorityQueue.peek()){
                    priorityQueue.remove();
                    priorityQueue.add(temp[i]);
                }
            }
        }

            return priorityQueue.peek();

        }

    public static void main(String[] args) {
        Solution solution=new Solution();
        int nums[]={1,2,2,5,3,5};
        int i = solution.thirdMax(nums);
        System.out.println(i);


    }


}

然后看官方的解答才知道如此简单

class Solution {
    public int thirdMax(int[] nums) {
        Arrays.sort(nums);
        reverse(nums);
        for (int i = 1, diff = 1; i < nums.length; ++i) {
            if (nums[i] != nums[i - 1] && ++diff == 3) { // 此时 nums[i] 就是第三大的数
                return nums[i];
            }
        }
        return nums[0];
    }

    public void reverse(int[] nums) {
        int left = 0, right = nums.length - 1;
        while (left < right) {
            int temp = nums[left];
            nums[left] = nums[right];
            nums[right] = temp;
            left++;
            right--;
        }
    }
}

作者:力扣官方题解
链接:https://leetcode.cn/problems/third-maximum-number/solutions/1032401/di-san-da-de-shu-by-leetcode-solution-h3sp/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值