成人国产在线小视频_日韩寡妇人妻调教在线播放_色成人www永久在线观看_2018国产精品久久_亚洲欧美高清在线30p_亚洲少妇综合一区_黄色在线播放国产_亚洲另类技巧小说校园_国产主播xx日韩_a级毛片在线免费

資訊專欄INFORMATION COLUMN

[LintCode] Top k Largest Numbers I

solocoder / 754人閱讀

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)允許請勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。

轉(zhuǎn)載請注明本文地址:http://systransis.cn/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 評論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 評論0 收藏0
  • [LintCode] Print Numbers by Recursion

    摘要:只有當(dāng)位數(shù)時,才打印數(shù)字。首先分析邊界,應(yīng)該,然后用存最高位。用函數(shù)對進(jìn)行遞歸運算,同時更新結(jié)果數(shù)組。更新的過程歸納一下,首先,計算最高位存入,然后,用到倍的和之前里已經(jīng)存入的所有的數(shù)個循環(huán)相加,再存入,更新,計算更高位直到等于 Problem Print numbers from 1 to the largest number with N digits by recursion. ...

    kumfo 評論0 收藏0
  • [LintCode] Kth Largest Element [PriorityQueue]

    摘要:可以不要用太簡單的方法。先把它裝滿,再和隊列頂端的數(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 評論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 評論0 收藏0

發(fā)表評論

0條評論

最新活動
閱讀需要支付1元查看
<