Search
 
SCRIPT & CODE EXAMPLE
 

JAVA

java find nth largest element using priority queue heap

public class MinHeap {

    public static int kthLargestElement(int k, int[] array){
        PriorityQueue<Integer> minHeap = new PriorityQueue<>();
        int size = array.length;
        for (int i = 0; i < size; i++){
            minHeap.add(array[i]);
            if (minHeap.size() > k){
                minHeap.poll();
            }
        }
        return minHeap.peek();
    }

    public static void main(String[] args) {
        int[] array = {7, 10, 4, 3, 20, 15, 2};
        System.out.println(MinHeap.kthLargestElement(3, array));
    }
}
Comment

java find nth smallest element using priority queue heap

public class MaxHeap {

    public static int  kthSmallestElement(int  k, int [] array){
        PriorityQueue<Integer> maxHeap = new  PriorityQueue<>(Collections.reverseOrder());
        int  length = array.length;
        for  (int  i = 0; i < length; i++){
            maxHeap.add(array[i]);
            if  (maxHeap.size() > k){
                maxHeap.poll();
            }
        }
        return  maxHeap.peek();
    }

    public static void  main(String[] args) {
        int [] array = {1, 3, 8, 9, 4, 7, 6};
        System.out .println(MaxHeap.kthSmallestElement(3, array));
    }
}
Comment

PREVIOUS NEXT
Code Example
Java :: arrays in constructor java 
Java :: find min max and average arraylist 
Java :: java quote of the day 
Java :: react-native maven package 404 not found 
Java :: print out list of letters a to z java 
Java :: math ceil java 
Java :: sending file over socket stream 
Java :: Java 8 merge multiple collections. 
Java :: download a website as string kotlin 
Java :: ggt euklidischer algorithmus java 
Java :: What Is Spring Boot and What Are Its Main Features? 
Java :: java tic tac toe gui based using applet 
Java :: We would like to make a member of a class can access in all subclasses regardless of what package the subclass is in. Which one of the following keywords would achieve this? 
Java :: Java Create an OutputStreamWriter 
Java :: how to create gravity in Java 
Java :: remove minimum element from stack java 
Java :: metodi di javascritp 
Java :: Java Method for Code Reusability 
Java :: java reverse nodes with single node 
Java :: connect 2 package in android 
Java :: java.lang.number is interface or abstract class 
Java :: text field background color swing 
Java :: Java socket connect to gmail 
Java :: how to print an array in TImber android 
Java :: create object of hashMap 
Java :: does not have a NavController set on 21312310 kotlin 
Java :: Array first Occurence 
Java :: java destroy object 
Java :: android how to get position of a row in listview 
Java :: output 
ADD CONTENT
Topic
Content
Source link
Name
6+2 =