[LintCode] Top k Largest Numbers I

Problem

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

Example

Given [3,10,1000,-99,4,100] and k = 3.
Return [1000, 100, 10].

Tags

Heap Priority Queue

Solution

public class Solution {
    public int[] topk(int[] nums, int k) {
 
        //construct comparator, then priority-queue
        Comparator comparator = new Comparator() {
            public int compare(Integer v1, Integer v2) {
                //can also use `return v2-v1;`
                if (v1 < v2) {
                    return 1;
                } else if (v1 > v2) {
                    return -1;
                } else {
                    return 0;
                }
            }
        };
        
        PriorityQueue maxHeap = new PriorityQueue<>(k, comparator);
        
        //use maxHeap to get top k largest
        for (int num: nums) {
            maxHeap.offer(num);
        }
        
        //save to res array
        int[] res = new int[k];
        for (int i = 0; i < k; i++) {
            res[i] = maxHeap.poll();
        }
        
        return res;
    }
}

你可能感兴趣的:(comparator,heap,priority-queue,java)