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.
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
Solutionpublic class Solution { /* * @param k: An integer */ Queuepq; 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
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 { ...
摘要:可以不要用太简单的方法。先把它装满,再和队列顶端的数字比较,大的就替换掉,小的就。遍历完所有元素之后,顶部的数就是第大的数。 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...
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...
摘要:和唯一的不同是组合中不能存在重复的元素,因此,在递归时将初始位即可。 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...
摘要:整个过程相当于,直接在和里去掉既是又是的。所以最后返回的,一定是只出现过一次的,而出现两次的都在里,出现三次的都被消去了。 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...
阅读 3114·2021-10-08 10:04
阅读 1026·2021-09-30 09:48
阅读 3407·2021-09-22 10:53
阅读 1616·2021-09-10 11:22
阅读 1645·2021-09-06 15:00
阅读 2112·2019-08-30 15:56
阅读 664·2019-08-30 15:53
阅读 2205·2019-08-30 13:04