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 :: how to check if a value is integer or not in java 
Java :: file with line numbers inserted java 
Java :: how to romve a element from arraylist in java 
Java :: jsonobject add key value java 
Java :: java default keyword 
Java :: java remove element from list 
Java :: check if combobox has specified value 
Java :: You may test the newly compiled and packaged JAR in maven 
Java :: Eclipse find/replace pluggin 
Java :: Java remove element in a array - set to null 
Java :: itext new page 
Java :: class BuildConfig is public, should be declared in a file named BuildConfig.java 
Java :: records java final 
Java :: multipleQuastion.Java 
Java :: textbox to arraylist 
Java :: how to get value from property file in spring xml file 
Java :: scanner class in java 
Java :: Example: My favorite cities 
Java :: spring core xml configuration for collection using constructor 
Java :: binary search 2D java 
Java :: pgzint install windows 10 
Java :: java optional input for funktions 
Java :: Java Multi-catch block 
Java :: how to refresh activity intent in android 
Java :: venatana emergente con texto java 
Java :: Labeled continue Statement Java 
Java :: how to do 4th root java 
Java :: javafx treeview directory 
Java :: how to validate information against the database in java 
Java :: /= java 
ADD CONTENT
Topic
Content
Source link
Name
1+6 =