Based PriorityQueue (PQ) to solve the problem TOP-K

TOP-K-frequency problem is the interview questions, i.e., find the maximum (or minimum data first k) in the mass data, the implied condition is insufficient memory to hold all the data, so the one-time data read into memory, sort, then Articles taken before k is unrealistic.

Here we use a simple code to solve Java8 TOP-K problem. In order to make more clear the main logic, removing some parameters, such as other non-critical code validity check.

PriorityQueue (PQ) is provided JDK1.5 start, including the lead author of the originator of the famous New York University professor Doug Lea, he is also Java JUC package oh.

PriorityQueue the equivalent of a stack (the default is small heap root, root if you want to create a big pile, then the reverse should be designated as the creation PriorityQueue, the code below)

new PriorityQueue<>(maxSize, Comparator.reverseOrder());

Here we are in default of a small pile to solve the root problem TOP-K (small heap root for solving a maximum top-k, and a large root heap for the k-th smallest value before solving)

class FixSizedPriorityQueue { // custom priority queue fixed length (k), so that the problem can be solved Top-k 
    PriorityQueue <Integer> Queue;
     int K;

    public FixSizedPriorityQueue(int k) {
        this.k = k;
        this.queue = new PriorityQueue<>(k);
    }

    public  void the Add (Integer E) {
         IF (queue.size () <k) { // the current queue element is less than the number of k, added directly 
            queue.add (e);
        } The else { // exceeds k of time 
            IF (e.compareTo (queue.peek ())> 0) { // If a new element is greater than the top of the stack element, the new element to be described replaces the current top of the stack elements 
                queue.poll ( );
                queue.add(e);
            }
        }
    }
}
public  class Main {

    public static void main(String[] args) {

        final FixSizedPriorityQueue pq = new FixSizedPriorityQueue(10);
        Random random = new Random();
        random.ints ( 100, 0, 1000) .forEach (PQ :: the Add); // generated 100 random numbers from 0 to 1000, fixed length and adding custom priority queue 
        the while (! pq.queue.isEmpty () ) {
            Of System.out.print (pq.queue.poll () + ","); // continue to remove the top of the stack element, since the present embodiment is a small heap root, therefore small to large print out the largest value in a 10 
        }
    }
}

 

 

 

Guess you like

Origin www.cnblogs.com/flamestudio/p/12000151.html