Java Workable Solution


  • 0
    J
    public int thirdMax(int[] nums) {
            if(nums.length == 0) return 0;
            int first = Integer.MIN_VALUE;
            int second = Integer.MIN_VALUE;
            int third = Integer.MIN_VALUE;
            int count = 0;
            boolean firstGot = false;
            boolean secondGot = false;
            for(int num : nums){
                if(num == first){
                    if(!firstGot){
                        count ++;
                        firstGot = true;
                    } 
                    continue;
                }
                if(num == second){
                    if(!secondGot){
                        count ++;
                        secondGot = true;
                    }
                    continue;
                }
                if(num > first){
                    third = second;
                    second = first;
                    first = num;
                    count ++;
                    if(firstGot)
                        secondGot = true;
                    else
                        firstGot = true;
                }else if(num > second){
                    third = second;
                    second = num;
                    count ++;
                    secondGot = true;
                }else if(num >= third){
                    third = num;
                    count ++;
                }
            }
            if(count >= 3) 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.