Given a non-empty array of integers, return the k most frequent elements.
Example 1:
Input: nums = [1,1,1,2,2,3], k = 2
Output: [1,2]
Example 2:
Input: nums = [1], k = 1
Output: [1]
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频率的数
解法一,利用排序,我们构造一个数据结构记录每个数的值和频率(类似的思想可以开一个堆,用堆操作)
class Solution { private class node implements Comparable<node>{ public int num; public int freq; public node(int num, int freq) { this.num = num; this.freq = freq; } @Override public int compareTo(node o) { if (this.freq < o.freq) return 1; if (this.freq > o.freq) return -1; return 0; } } public List<Integer> topKFrequent(int[] nums, int k) { HashMap<Integer, Integer> map = new HashMap<>(); for(int n: nums){ map.put(n, map.getOrDefault(n,0)+1); } List<Integer> res = new ArrayList<>(k); node[] nodes = new node[map.size()]; int i = 0; for (Map.Entry entry: map.entrySet()) { int num = (int) entry.getKey(); int freq = (int) entry.getValue(); node nd = new node(num, freq); nodes[i] = nd; i++; } Arrays.sort(nodes); for (i = 0; i < k; i++) { res.add(nodes[i].num); } return res; } }
解法二:利用TreeMap,TreeMap是基于红黑树的,自排序,注意一点就是你要排序的对象就行了
public class Solution { public List<Integer> topKFrequent(int[] nums, int k) { HashMap<Integer, Integer> map = new HashMap<>(); for(int n: nums){ map.put(n, map.getOrDefault(n,0)+1); } TreeMap<Integer, List<Integer>> fremap = new TreeMap<>(); for (int num : map.keySet()) { if (!fremap.containsKey(map.get(num))) { fremap.put(map.get(num), new LinkedList<>()); } fremap.get(map.get(num)).add(num); } List<Integer> res = new ArrayList<>(); while (res.size() < k) { Map.Entry<Integer, List<Integer>> entry = fremap.pollLastEntry(); res.addAll(entry.getValue()); } return res; } }