Simple Java solution using 3 for loops


  • 0
    N
    public class Solution {
        public int thirdMax(int[] nums) {
            int max1 =0,max2=0,max3=Integer.MIN_VALUE;
            boolean found =false;
            for(int i=0;i<nums.length;i++){
              max1 = Math.max(max1,nums[i]);
            }
             for(int i=0;i<nums.length;i++){
              if(nums[i]!=max1)         
              max2 = Math.max(max2,nums[i]);
            }
             for(int i=0;i<nums.length;i++){
              if(nums[i]!=max2 && nums[i]!=max1){  
              max3 = Math.max(max3,nums[i]);
              found =true;
              }
            }
            if(max2==0||!found)
            return max1;
            
          
          return max3;
        }
    }

Log in to reply
 

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