Java 4ms naive solution. No extra data structures, just comparing numbers


  • 0

    Since this problem only asks for 3 numbers, I use the most naive way to solve it.
    If they are more numbers, it is better to use some other data structures or use quick select to solve. (kth smallest or biggest)
    Here is the code.

    public int thirdMax(int[] nums) {
        if(nums.length==1) return nums[0];
        if(nums.length==2) return nums[0]>nums[1]?nums[0]:nums[1];
        int first = Integer.MIN_VALUE;
        int second = Integer.MIN_VALUE;
        int third = Integer.MIN_VALUE;
        boolean minval = false;
        for(int num:nums){
            if(num==Integer.MIN_VALUE) minval=true;
            //since I use MIN_INT as the initial value, need to check it here
            if(num>third&&num!=first&&num!=second){
                third = num;
            }
            //reorder first, second, third
            if(third>second){
                int temp = second;
                second = third;
                third = temp;
            }
            if(second>first){
                int temp = first;
                first = second;
                second = temp;
            }
        }
        if(third!=Integer.MIN_VALUE||(minval==true&&second!=Integer.MIN_VALUE)){
            return third;
        }
        else{
            return first;
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.