leetcode347 Top K Frequent Elements java

来源:互联网 发布:数组下标-1 编辑:程序博客网 时间:2024/06/16 13:23

欢迎转载,转载请注明原地址:
http://blog.csdn.net/u013190088/article/details/66995597


Description

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.

解法:

首先想到的就是用map存储数字以及其出现的次数。之后将次数作为数组下标,根据次数把数字分到若干个“桶”(数组中的每个位置都相当于一个“桶”)里边,最后从后向前遍历数组即可。

public List<Integer> topKFrequent(int[] nums, int k) {        Map<Integer, Integer> map = new HashMap<>();        List<Integer>[] arr = new List[nums.length + 1];        for(int n : nums) {            map.put(n, map.getOrDefault(n,0) + 1);        }        for(int key : map.keySet()) {            int frequency = map.get(key);            if(arr[frequency] == null) arr[frequency] = new ArrayList<>();            arr[frequency].add(key);        }        List<Integer> res = new ArrayList<>();        for(int j=arr.length-1; res.size()<k; j--) {            if(arr[j] != null) {                res.addAll(arr[j]);            }        }        return res;    }
0 0
原创粉丝点击