Java solution


  • 0

    Critical part is to avoid duplicate numbers.

    public int thirdMax(int[] nums) {
            if(nums==null||nums.length==0) return Integer.MIN_VALUE;
            int len=nums.length;
            if(len==1) return nums[0];
            if(len==2) return Math.max(nums[0],nums[1]);
            int a=nums[0], i=1;
            while(i<len&&nums[i]==nums[i-1]) i++;
            if(i==len) return a;
            int b=nums[i];
            int  max1=Math.max(a,b), max2=Math.min(a,b), max3=Integer.MIN_VALUE;
            boolean flag=false;//indicate whether max3 is valid
            for(i=i+1;i<len;i++){
                if(nums[i]==max1||nums[i]==max2) continue;
                flag=true;
                if(nums[i]>max1){
                    max3=max2;
                    max2=max1;
                    max1=nums[i];
                }else if(nums[i]>max2){
                    max3=max2;
                    max2=nums[i];
                }else if(nums[i]>max3){
                    max3=nums[i];
                }
            }
            return flag?max3:Math.max(max1,max2);
        }
    

Log in to reply
 

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