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
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
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
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:
import java.util.Arrays; import java.util.List; public class TestKBest{ public static void main(String[] args) { int k = 5; KBestCounter counter = new KBestCounter<>(k); System.out.println("Inserting 1,2,3."); for(int i = 1; i<=3; i++) counter.count(i); System.out.println("5-best should be [3,2,1]: "+counter.kbest()); counter.count(2); System.out.println("Inserting another 2."); System.out.println("5-best should be [3,2,2,1]: "+counter.kbest()); System.out.println("Inserting 4..99."); for (int i = 4; i < 100; i++) counter.count(i); System.out.println("5-best should be [99,98,97,96,95]: " + counter.kbest()); System.out.println("Inserting 100, 20, 101."); counter.count(100); counter.count(20); counter.count(101); System.out.println("5-best should be [101,100,99,98,97]: " + counter.kbest()); } } Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
