Heap solution. A little better than sorting. O(N + Nlogk)


  • 0
    E
    public class Solution {
        public int thirdMax(int[] nums) {
            HashSet<Integer> set = new HashSet<>();
            PriorityQueue<Integer> q = new PriorityQueue<>(3,Collections.reverseOrder());
            int result = 0, k = 0;
    
            for(int i : nums) set.add(i);
            for(int j : set) q.add(j);
            
            if(q.size() < 3 && !q.isEmpty()) return q.poll();
                   
            while(k < 3){
              if(!q.isEmpty()) 
                result = q.poll();
                k++;
            }
            return result;
        }
    }

Log in to reply
 

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