zoukankan      html  css  js  c++  java
  • [leetcode]347. Top K Frequent Elements 最高频的K个元素

    Given a non-empty array of integers, return the k most frequent elements.

    For example,
    Given [1,1,1,2,2,3] and k = 2, return [1,2].

    Note: 

      • You may assume k is always valid, 1 ≤ k ≤ number of unique elements.
      • Your algorithm's time complexity must be better than O(n log n), where n is the array's size.

    题意:

    给定数组,求其中出现频率最高的K个元素。

    Solution: PriorityQueue

    扫数组,将数组每个元素和其对应的出现频率存到Map里

    扫Map,将Map里的元素放入maxHeap

    从maxHeap里poll出K个元素即可

    code

     1 class Solution {
     2     public List<Integer> topKFrequent(int[] nums, int k) {
     3         Map<Integer, Integer> numFreqs = new HashMap();
     4         
     5         for(int num : nums){
     6             numFreqs.put(num, numFreqs.containsKey(num) ? numFreqs.get(num) + 1 : 1);
     7         }
     8         
     9         PriorityQueue <Map.Entry<Integer, Integer>> maxHeap = new PriorityQueue<>((entry1, entry2) -> entry2.getValue() - entry1.getValue());
    10         
    11         
    12         for(Map.Entry<Integer, Integer> entry : numFreqs.entrySet()){
    13             maxHeap.add(entry);
    14         }
    15         
    16         List<Integer> result = new ArrayList<>();
    17         while(!maxHeap.isEmpty() && result.size() < k){
    18             result.add(0, maxHeap.poll().getKey());
    19         }
    20         return result;
    21         
    22     }
    23 }
  • 相关阅读:
    [BZOJ1015] [JSOI2008]星球大战starwar
    [BZOJ2321,LuoguP1861]星(之)器
    Google Search Operators
    Python blockchain
    CCAE词频表(转)
    python小技巧(转)
    Python著名的lib和开发框架(均为转载)
    Yarn取代job/task tracker
    hadoop 2.73‘s four xml
    HDFS NN,SNN,BN和HA
  • 原文地址:https://www.cnblogs.com/liuliu5151/p/9158270.html
Copyright © 2011-2022 走看看