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; } }
文章版權(quán)歸作者所有,未經(jīng)允許請勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉(zhuǎn)載請注明本文地址:http://specialneedsforspecialkids.com/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 { ...
摘要:可以不要用太簡單的方法。先把它裝滿,再和隊列頂端的數(shù)字比較,大的就替換掉,小的就。遍歷完所有元素之后,頂部的數(shù)就是第大的數(shù)。 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...
摘要:和唯一的不同是組合中不能存在重復(fù)的元素,因此,在遞歸時將初始位即可。 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...
摘要:整個過程相當(dāng)于,直接在和里去掉既是又是的。所以最后返回的,一定是只出現(xiàn)過一次的,而出現(xiàn)兩次的都在里,出現(xiàn)三次的都被消去了。 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...
閱讀 3142·2021-10-08 10:04
閱讀 1080·2021-09-30 09:48
閱讀 3449·2021-09-22 10:53
閱讀 1664·2021-09-10 11:22
閱讀 1682·2021-09-06 15:00
閱讀 2142·2019-08-30 15:56
閱讀 704·2019-08-30 15:53
閱讀 2273·2019-08-30 13:04