资讯专栏INFORMATION COLUMN

[LintCode] Top k Largest Numbers II

jindong / 1984人阅读

Problem

Implement a data structure, provide two interfaces:

add(number). Add a new number in the data structure.
topk(). Return the top k largest numbers in this data structure. k is given when we create the data structure.

Example
s = new Solution(3);
>> create a new data structure.
s.add(3)
s.add(10)
s.topk()
>> return [10, 3]
s.add(1000)
s.add(-99)
s.topk()
>> return [1000, 10, 3]
s.add(4)
s.topk()
>> return [1000, 10, 4]
s.add(100)
s.topk()
>> return [1000, 100, 10]
Tags

Heap Priority Queue

Solution
public class Solution {
    /*
    * @param k: An integer
    */
    Queue pq;
    int size;
    public Solution(int k) {
        // do intialization if necessary
        pq = new PriorityQueue();
        size = k;
    }

    /*
     * @param num: Number to be added
     * @return: nothing
     */
    public void add(int num) {
        // write your code here
        if (pq.size() < size) pq.offer(num);
        else if (pq.peek() < num) {
            pq.poll();
            pq.offer(num);
        }
        return;
    }

    /*
     * @return: Top k element
     */
    public List topk() {
        // write your code here
        Iterator it = pq.iterator();
        List res = new ArrayList<>();
        while (it.hasNext()) {
            res.add((Integer) it.next());
        }
        Collections.sort(res, Collections.reverseOrder());
        return res;
    }
}

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/68577.html

相关文章

  • [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 { ...

    solocoder 评论0 收藏0
  • [LintCode] Kth Largest Element [PriorityQueue]

    摘要:可以不要用太简单的方法。先把它装满,再和队列顶端的数字比较,大的就替换掉,小的就。遍历完所有元素之后,顶部的数就是第大的数。 Problem Find K-th largest element in an array. Example In array [9,3,2,4,8], the 3rd largest element is 4.In array [1,2,3,4,5], the...

    Hwg 评论0 收藏0
  • [LeetCode/LintCode] Largest Palindrome Product

    Problem Find the largest palindrome made from the product of two n-digit numbers. Since the result could be very large, you should return the largest palindrome mod 1337. Example Input: 2Output: 987Ex...

    Barry_Ng 评论0 收藏0
  • [LintCode/LeetCode] Combination Sum I & II

    摘要:和唯一的不同是组合中不能存在重复的元素,因此,在递归时将初始位即可。 Combination Sum I Problem Given a set of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T...

    ThreeWords 评论0 收藏0
  • [LintCode/LeetCode] Single Number I & II [位运算]

    摘要:整个过程相当于,直接在和里去掉既是又是的。所以最后返回的,一定是只出现过一次的,而出现两次的都在里,出现三次的都被消去了。 Single Number I Problem Given 2*n + 1 numbers, every numbers occurs twice except one, find it. Example Given [1,2,2,1,3,4,3], return...

    Drinkey 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<