国产xxxx99真实实拍_久久不雅视频_高清韩国a级特黄毛片_嗯老师别我我受不了了小说

資訊專欄INFORMATION COLUMN

[LintCode] Top k Largest Numbers I

solocoder / 702人閱讀

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 {
    public int[] topk(int[] nums, int k) {
 
        //construct comparator, then priority-queue
        Comparator comparator = 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

相關(guān)文章

  • [LintCode] Top k Largest Numbers II

    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...

    jindong 評(píng)論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 評(píng)論0 收藏0
  • [LintCode] Print Numbers by Recursion

    摘要:只有當(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. ...

    kumfo 評(píng)論0 收藏0
  • [LintCode] Kth Largest Element [PriorityQueue]

    摘要:可以不要用太簡(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...

    Hwg 評(píng)論0 收藏0
  • [LintCode/LeetCode] Check Sum of K Primes

    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...

    lakeside 評(píng)論0 收藏0

發(fā)表評(píng)論

0條評(píng)論

最新活動(dòng)
閱讀需要支付1元查看
<