Java Solution using TreeMap


  • 0
    S
    public class Solution {
        public int thirdMax(int[] nums) {
            TreeMap<Integer,Integer> map = new TreeMap(Collections.reverseOrder());
            for(int num:nums){
                map.put(num,1);
            }
            int index=2,max=0;
            int loopCounter=0;
            int size = map.size();//check if input has no third max.
            if(size<3)
                index=0;
            for(Map.Entry<Integer,Integer> i :map.entrySet()){
                if(loopCounter==index){
                    max = i.getKey();
                }
                //System.out.printf("Loop counter:%d,Max:%d\n",loopCounter,max);
                loopCounter++;
            }
            return max;
        }
    }
    

Log in to reply
 

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