Elegant Java solution using Max-Heap


  • 1
    A
    public int findKthLargest(int[] nums, int k) {
           //Max Heap
           PriorityQueue<Integer> heap = new PriorityQueue<Integer>(new Comparator<Integer>(){
               public int compare(Integer a, Integer b){
                   return -1* a.compareTo(b);
               }
           });
           
           for(int val: nums){
               heap.add(val);
           }
           int kElement = 0;
           for(int i = 0; i < k; i++){
               kElement = heap.poll();
           }
           
           return kElement;
           
       }
    

    TimeComplexity O(nLog(n))
    SpaceComplexity O(n)


Log in to reply
 

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