Find smallest 100 numbers from a very long input

Solution)

Using a Priority Queue (Max heap), we can create it with an initial capacity 100.

By traversing all inputs, we can add it to the priority queue if the number is less then the peek of the priority queue.

For example, we have the following inputs.

[10,2,5,8,1,4,7] and initial capacity is 4

Priority queue can manage all orders by sorting.

[10]

[10,2]

[10,5,2]

[10,8,5,2]

Now the queue reaches the capacity.

The next number is 1 which is less then 10 which is peek of the queue.

We have to remove 10 and then insert 1 to the queue

[8,5,2,1]

[5,4,2,1]

Finally, the queue is [5,4,2,1]

We have to create a result by iterator the queue.

public int[] findSmallestNumbers(int[] nums, int count) {
    if (nums == null || nums.length == 0) return new int[0];
    PriorityQueue<Integer> pq = new PriorityQueue<>(count, (a,b -> b-a));
    pq.offer(nums[0]);
    for (int i = 1; i < nums.length; i++) {
        if (pq.peek() > nums[i]) {
            if (pq.size() == count) qp.poll();
            pq.offer(nums[i]);
        }
    }
    int[] result = new int[pq.size()];
    Iterator<Integer> it = pq.iterator();
    for (int i = result.length-1; i >= 0; i--)
        result[i] = it.next();
    }
    return result;
}

results matching ""

    No results matching ""