zoukankan      html  css  js  c++  java
  • LeetCode 347. Top K Frequent Elements

    原题链接在这里:https://leetcode.com/problems/top-k-frequent-elements/

    题目:

    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.

    题解:

    先计算出element 和对应的frequency.

    然后使用bucket sort. 把element按照出现频率放在bucket中.

    因为一共只有n 个元素, 那么最大的频率只能是n. n = nums.length. 所以bucket的大小是n+1, 才能对应最大频率.

    然后从bucket后扫到前,因为后面的elements 频率高. 加到res中直到res的size到达k.

    Note: bucket的生成等号右边是ArrayList[] 而不能是ArrayList<Integer>[], 因为complier 不能判准加进ArrayList中的type, 只有run time才能知道. 所以这里complier不允许确定type.

    Time Complexity: O(n), n = nums.length.

    Space: O(n).

    AC Java:

     1 class Solution {
     2     public List<Integer> topKFrequent(int[] nums, int k) {
     3         List<Integer> res = new ArrayList<Integer>();
     4         if(nums == null || nums.length == 0){
     5             return res;
     6         }
     7         
     8         HashMap<Integer, Integer> hm = new HashMap<Integer, Integer>();
     9         for(int num : nums){
    10             hm.put(num, hm.getOrDefault(num, 0)+1);
    11         }
    12         
    13         ArrayList [] buckets= new ArrayList[nums.length+1];
    14         for(Map.Entry<Integer, Integer> entry : hm.entrySet()){
    15             int freq = entry.getValue();
    16             if(buckets[freq] == null){
    17                 buckets[freq] = new ArrayList<Integer>();
    18             }
    19             buckets[freq].add(entry.getKey());
    20         }
    21         
    22         for(int i = buckets.length-1; i>=0 && res.size()<k; i--){
    23             if(buckets[i] != null){
    24                 res.addAll(buckets[i]);
    25             }
    26         }
    27         
    28         return res;
    29     }
    30 }

    类似Sort Characters By FrequencyTop K Frequent WordsK Closest Points to Origin.

  • 相关阅读:
    Windows Server 2012 64bit RMAN异机不完全恢复(迁移)
    dbms_jobs vs. dbms_scheduler_jobs
    Migrating from dbms_job to dbms_scheduler
    ORA-12537: TNS:connection closed
    win7 ins 30131 oracle 12c
    Vector源码分析
    LinkedList源码分析
    ArrayList源码分析
    jsp 显示日期
    Spring data redis 使用 pipelined 批量操作
  • 原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/6362017.html
Copyright © 2011-2022 走看看