Java Solution Using TreeSet


  • 6
    D
    public class Solution {
        public final int N = 3;
        public int thirdMax(int[] nums) {
            if (nums.length == 0) return 0;
    
            TreeSet<Integer> set = new TreeSet<Integer>();
            for (int i = 0; i < nums.length; i++) {
                if (set.contains(nums[i])) continue;
                if (set.size() < N || nums[i] > set.first()) {
                    if (set.size() == N) set.remove(set.first());
                    set.add(nums[i]);
                }
            }
            return set.size() == N ? set.first() : set.last();
        }
    }
    

  • 0
    M

    What is the time complexity of your solution ? Since most basic operation of treeset is log n, is that a n * long(n) for your solution?


  • 0
    D
    This post is deleted!

  • 0
    D

    @mustangigem the Tree set size is limited to 3, so it's O(n).


Log in to reply
 

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