Short Java Solution Using TreeSet


  • 0

    Set has a good property: duplicate values won't be stored in set.
    TreeSet has a good property: it is ordered.
    Cause the set only contains at most 3 values, so it is n*log(3)

    public int thirdMax(int[] nums) {
        TreeSet<Integer> set = new TreeSet<Integer>();
        for(int num : nums) {
            set.add(num);
            if(set.size()>3)
                set.pollFirst();
        }
        return set.size() < 3 ? set.last() : set.first();
    }

Log in to reply
 

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