Problem
Given an integer array, find the top k largest numbers in it.
ExampleGiven [3,10,1000,-99,4,100] and k = 3.
Return [1000, 100, 10].
Heap Priority Queue
Solutionpublic class Solution { public int[] topk(int[] nums, int k) { //construct comparator, then priority-queue Comparatorcomparator = 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; } }
文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。
转载请注明本文地址:https://www.ucloud.cn/yun/68082.html
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 crea...
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...
摘要:只有当位数时,才打印数字。首先分析边界,应该,然后用存最高位。用函数对进行递归运算,同时更新结果数组。更新的过程归纳一下,首先,计算最高位存入,然后,用到倍的和之前里已经存入的所有的数个循环相加,再存入,更新,计算更高位直到等于 Problem Print numbers from 1 to the largest number with N digits by recursion. ...
摘要:可以不要用太简单的方法。先把它装满,再和队列顶端的数字比较,大的就替换掉,小的就。遍历完所有元素之后,顶部的数就是第大的数。 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 Given two numbers n and k. We need to find out if n can be written as sum of k prime numbers. Example Given n = 10, k = 2Return true // 10 = 5 + 5 Given n = 2, k = 2Return false Solution pub...
阅读 2471·2021-11-24 09:39
阅读 3516·2019-08-30 15:53
阅读 593·2019-08-29 15:15
阅读 2902·2019-08-26 13:23
阅读 3211·2019-08-26 10:48
阅读 642·2019-08-26 10:31
阅读 747·2019-08-26 10:30
阅读 2358·2019-08-23 18:32