O(n) simple java solution


  • 0
    S

    public class Solution {
    public int thirdMax(int[] nums) {
    int max1 = Integer.MIN_VALUE;
    int max2 = Integer.MIN_VALUE;
    int max3 = Integer.MIN_VALUE;

        int found = 0;
        
        for(int num : nums) {
            if(num > max1 || found < 1) {
                max3 = max2;
                max2 = max1;
                max1 = num;
                found++;
            } else if(num != max1) {
                if(num > max2 || found < 2) {
                    max3 = max2;
                    max2 = num;
                    found++;
                } else if(num != max2 && (num > max3 || found < 3)) {
                    max3 = num;
                    found++;
                }
            }
        }
        
        if(found < 3)
            return max1;
            
        return max3;
        
    }
    

    }


Log in to reply
 

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