Advertisement
Guest User

Untitled

a guest
Jul 29th, 2016
53
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.53 KB | None | 0 0
  1. public class Solution {
  2. public List<Integer> topKFrequent(int[] nums, int k) {
  3. List<Integer> result = new ArrayList<>();
  4. if (nums == null || nums.length == 0) {
  5. return result;
  6. }
  7.  
  8. // step 1: count the freq of each word
  9. Map<Integer, Integer> map = new HashMap<>();
  10. for (int num : nums) {
  11. if (map.containsKey(num)) {
  12. int freq = map.get(num);
  13. map.put(num, freq + 1);
  14. } else {
  15. map.put(num, 1);
  16. }
  17. }
  18.  
  19. // step 2: use a min-heap to get the top k frequencies.
  20. PriorityQueue<Pair> pq = new PriorityQueue<>(new MyPQComparator());
  21. int count = 0;
  22. for (int word : map.keySet()) {
  23. int freq = map.get(word);
  24. Pair pair = new Pair(freq, word);
  25. if (count < k) {
  26. pq.offer(pair);
  27. } else if (pair.freq > pq.peek().freq) {
  28. pq.poll();
  29. pq.offer(pair);
  30. }
  31. count++;
  32. }
  33.  
  34. // step 3: output the result
  35. for (Pair pair : pq) {
  36. result.add(pair.word);
  37. }
  38.  
  39. return result;
  40. }
  41.  
  42. private class MyPQComparator implements Comparator<Pair> {
  43. @Override
  44. public int compare(Pair a, Pair b) {
  45. return a.freq - b.freq;
  46. }
  47. }
  48. }
  49.  
  50. class Pair {
  51. int word;
  52. int freq;
  53.  
  54. Pair(int freq, int word) {
  55. this.word = word;
  56. this.freq = freq;
  57. }
  58. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement