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

    本题有一个要求就是算法时间复杂度要好于nlongn,本题看了答案才知道使用bucket的方法做出来,首先,bucket是把问题分成数组长度+1的等份,然后将数组输入到hashmap里面,其中value值代表的是出现该值的频率,然后遍历hashmap的key值,将其放入到其value对应的bucket数组里面,代码如下:

     1 public class Solution {
     2     public List<Integer> topKFrequent(int[] nums, int k) {
     3         List<Integer> res = new ArrayList<Integer>();
     4         List<Integer>[] frequency = new List[nums.length+1];
     5         Map<Integer,Integer> map = new HashMap<Integer,Integer>();
     6         for(int num:nums){
     7             map.put(num,map.getOrDefault(num,0)+1);
     8         }
     9         for(int key:map.keySet()){
    10             if(frequency[map.get(key)]==null){
    11                 frequency[map.get(key)] = new ArrayList<Integer>();
    12             }
    13             frequency[map.get(key)].add(key);
    14         }
    15         for(int i=frequency.length-1;i>=0&&res.size()<k;i--){
    16             if(frequency[i]!=null){
    17                 res.addAll(frequency[i]);
    18             }
    19         }
    20         return res.subList(0,k);
    21     }
    22 }
  • 相关阅读:
    spring学习之模拟spring(spring原理解析)-01.xml文件的解析
    存储过程学习
    对象的深浅拷贝
    JavaScript 面向对象编程思想(二)
    深层剖析JavaScript 一
    深入剖析 css
    Vuex 总结
    h5 微信授权
    LeetCode
    echarts-liquidfill
  • 原文地址:https://www.cnblogs.com/codeskiller/p/6592589.html
Copyright © 2020-2023  润新知