Given an integer array, find the top k largest numbers in it.

Example
Example1
Input: [3, 10, 1000, -99, 4, 100] and k = 3
Output: [1000, 100, 10]
Example2
Input: [8, 7, 6, 5, 4, 3, 2, 1] and k = 5
Output: [8, 7, 6, 5, 4]
public class Solution {
    /**
     * @param nums: an integer array
     * @param k: An integer
     * @return: the top k largest numbers in array
     */
    public int[] topk(int[] nums, int k) {
        // write your code here

        if(nums == null || nums.length == 0) return null;

        int[] res = new int[k];
        Queue<Integer> heap = new PriorityQueue<>();

        for(int i = 0; i < nums.length; i++) {
            if(heap.size() < k) {
                heap.add(nums[i]);
            } else {
                if(nums[i] > heap.peek()) {
                    heap.poll();
                    heap.add(nums[i]);
                }
            }
        }

        for(int i = k-1; i >= 0; i--) {
            res[i] = heap.poll();
        }

        return res;
    }
}

results matching ""

    No results matching ""