Saturday, February 13, 2021

Largest K numbers in a million numbers which are in random order

 Let's find out largest k numbers in a million numbers which are in random order

Sol:

public static void largestKNumbers(Integer[] a, int k) {

PriorityQueue<Integer> minHeap = new PriorityQueue<Integer>(k);

for(int i=0; i<k; i++) {

minHeap.add(a[i]);

}

for(int i=k; i < a.length; i++) {

if (a[i] > minHeap.peek()) {

minHeap.poll();

minHeap.add(a[i]);

}

}

Iterator iterator = minHeap.iterator();

while(iterator.hasNext()) {

System.out.print(iterator.next() + " ");

}

}


No comments:

Post a Comment