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; } }
文章版權(quán)歸作者所有,未經(jīng)允許請(qǐng)勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉(zhuǎn)載請(qǐng)注明本文地址:http://specialneedsforspecialkids.com/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...
摘要:只有當(dāng)位數(shù)時(shí),才打印數(shù)字。首先分析邊界,應(yīng)該,然后用存最高位。用函數(shù)對(duì)進(jìn)行遞歸運(yùn)算,同時(shí)更新結(jié)果數(shù)組。更新的過(guò)程歸納一下,首先,計(jì)算最高位存入,然后,用到倍的和之前里已經(jīng)存入的所有的數(shù)個(gè)循環(huán)相加,再存入,更新,計(jì)算更高位直到等于 Problem Print numbers from 1 to the largest number with N digits by recursion. ...
摘要:可以不要用太簡(jiǎn)單的方法。先把它裝滿,再和隊(duì)列頂端的數(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 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...
閱讀 2472·2021-11-24 09:39
閱讀 3518·2019-08-30 15:53
閱讀 594·2019-08-29 15:15
閱讀 2903·2019-08-26 13:23
閱讀 3212·2019-08-26 10:48
閱讀 643·2019-08-26 10:31
閱讀 748·2019-08-26 10:30
閱讀 2359·2019-08-23 18:32