Java TreeSet O(n) time O(1) space


  • 0
    M
    public class Solution {
        //o(nlog3)
        public int thirdMax(int[] nums) {
            if(nums == null || nums.length == 0) return 0;
            TreeSet<Integer> q = new TreeSet<Integer>();
            for(int i : nums){
                q.add(i);
                if(q.size() > 3) q.pollFirst();
            }
            if(q.size() == 3) return q.pollFirst();
            int rt = 0;
            while(!q.isEmpty()) rt = q.pollFirst();
            return rt;
        }
          
    }
    

Log in to reply
 

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