题414、第三大的数

一、题目1

在这里插入图片描述

二、思路

没啥好说的,就是将前三大的数存下来就行了,注意最后的测试集里面有Integer.MIN_VALUE,注意处理好就行了。

三、代码

import java.util.*;

public class T0414 {

    public T0414(){

//        int[] nums = {1,2,-2147483648};
//        int[] nums = {3, 2, 1};
//        int[] nums = {2, 1};
//        int[] nums = {7, 2, 3,5 , 4, 1, 5, 3, 3, 7, 2, 1, 2, 6, 7, 4, 3, 3, 6, 5, 4, 3, 5};
//        int[] nums = {1,2,2,5,3,5};
        int[] nums = {1,-2147483648,2};

        System.out.println( thirdMax( nums ) );
    }

    public int thirdMax(int[] nums) {

        int first = Integer.MIN_VALUE;
        int second = Integer.MIN_VALUE;
        int third = Integer.MIN_VALUE;
        int flag = 0;

        for ( int num : nums ){

            if ( num > first ){
                if ( second > Integer.MIN_VALUE )
                    flag = 1;
                third = second;
                second = first;
                first = num;

            }else if ( num > second ){

                if ( num == first )
                    continue;

                if ( second > Integer.MIN_VALUE )
                    flag = 1;
                third = second;
                second = num;
            }else if ( num >= third ){

                if(num == second && num > Integer.MIN_VALUE){
                    continue;
                }
                flag = 1;
                third = num;
            }

            System.out.println( first + "\t " + second + "\t " + third );

        }


        if ( second == Integer.MIN_VALUE ||  flag == 0 ){
            return first;
        }else
            return third;


    }

    //简单的
    public int thirdMax1(int[] nums) {

        Arrays.sort( nums );

        List<Integer> list = new ArrayList<>( 3 );

        int i = nums.length-1;

        while ( list.size() < 3 && i >= 0 ){
            if ( !list.contains( nums[i] ) )
                list.add( nums[i--] );
            else
                i--;
        }

        System.out.println( list );

        if ( list.size() == 3 )
            return list.get( 2 );
        else
            return list.get( 0 );
    }

    public static void main(String[] args) {
        T0414 t0414 = new T0414();
    }
}


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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值