标签:
For example,
Given [1,1,1,2,2,3]
and k = 2, return [1,2]
.
Note:
Subscribe to see which companies asked this question
public List<Integer> topKFrequent(int[] nums, int k) { List<Integer>[] bucket = new List[nums.length + 1]; Map<Integer, Integer> frequencyMap = new HashMap<Integer, Integer>(); for (int n : nums) { frequencyMap.put(n, frequencyMap.getOrDefault(n, 0) + 1); } for (int key : frequencyMap.keySet()) { int frequency = frequencyMap.get(key); if (bucket[frequency] == null) { bucket[frequency] = new ArrayList<>(); } bucket[frequency].add(key); } List<Integer> res = new ArrayList<>(); for (int pos = bucket.length - 1; pos >= 0 && res.size() < k; pos--) { if (bucket[pos] != null) { res.addAll(bucket[pos]); } } return res; }
public class Solution { public List<Integer> topKFrequent(int[] nums, int k) { HashMap<Integer, Integer> m = new HashMap<Integer, Integer>(); for(int i = 0; i<nums.length; ++i) { Integer count = m.get(nums[i]); if(count == null) { m.put(nums[i], 1); } else { m.put(nums[i], count+1); } } PriorityQueue<int[]> pq = new PriorityQueue<int[]>(k, new Comparator<int[]>(){ @Override public int compare(int[] a1, int[] a2) { return a1[1] - a2[1]; } } ); for(Map.Entry<Integer, Integer> entry : m.entrySet()) { if(pq.size() < k) pq.add(new int[]{entry.getKey(), entry.getValue()}); else if(pq.peek()[1]<entry.getValue()) { pq.remove(); pq.add(new int[]{entry.getKey(), entry.getValue()}); } } LinkedList<Integer> ret = new LinkedList<Integer>(); while(!pq.isEmpty()) { ret.push(pq.remove()[0]); } return ret; } }
标签:
原文地址:http://www.cnblogs.com/neweracoding/p/5539510.html