Please read carefully, will rate. THE METHODS BELOW NEED TO BE USE Finding the k
ID: 3683776 • Letter: P
Question
Please read carefully, will rate.
THE METHODS BELOW NEED TO BE USE
Finding the k-largest values in a set of data - Assume you are given a sequence of values. We do not know how many elements there are in this sequence. In fact, there could be infinitely many. Implement the class KBestCounter<T extends Comparable <? super T>> that keeps track of the k-largest elements seen so far in a set of data. The class should have two methods:
public void count(T x) - process the next element in the set of data. This operation should run in the at worst O(log k) time.
public List kbest() - return a sorted (largest to smallest) list of the k largest elements. This should run in O(k log k) time. The method should restore the priority queue to its original state after retrieving the klargest elements. If you run this method twice in a row, it should return the same values.
Use a Priority Queue to implement this functionality. We suggest using the built-in java.util.PriorityQueue, which implements a min-heap for you. You should never have more than k elements inserted into the Priority Queue at any given time.
import java.util.PriorityQueue;
public class KBestCounter<T extends Comparable <? super T>> {
PriorityQueue heap;
int k;
public KBestCounter(int k) {
//todo
}
public void count(T x) {
//todo
}
public List kbest() {
//todo
}
}
An example illustrates how KBestCounter could be used in this attached tester class:
Explanation / Answer
Min heap using Priority Queue:
import java.util.PriorityQueue; public class MinHeap_PQ { PriorityQueue<Integer> pq; public MinHeap_PQ() { pq = new PriorityQueue<Integer>(); } public void insert(int[] x) { for (int i = 0; i < x.length; i++) { pq.offer(x[i]); } } public int peek() { return pq.peek(); } public int extractMin() { return pq.poll(); } public int getSize() { return pq.size(); } public void print() { System.out.println(pq); } public static void main(String[] args) { int[] arrA = { 1, 6, 2, 9, 4, 3, 8 }; MinHeap_PQ i = new MinHeap_PQ(); i.insert(arrA); i.print(); System.out.println("Min Element in the Priority Queue: " + i.extractMin()); System.out.println("Min Element in the Priority Queue: " + i.extractMin()); System.out.println("Min Element in the Priority Queue: " + i.extractMin()); System.out.println("Priority Queue Size: " + i.getSize());
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.