## Thursday, February 25, 2016

### Top k elements with most occurrences - Cracking Code

Top k elements with most occurrences – Cracking Code
Find k elements within a array with most occurrences.

1. public static void main(String[] args) {
2. int[] nums = {1,1,2,2,3,3,3,4,5,6,6,6,6,6,7,7,7,8,8,8,8,9,10,11,12,13,14,15,15};
3. System.out.println(get(nums, 3));
4. }
5. public static List<Integer> get(int[] nums, int k) {
6. List<Integer> result = new ArrayList<>();
7. if (nums == null || nums.length == 0 || k == 0) return result;
8.
9.
10. HashMap<Integer, Integer> map = new HashMap<>();
11. for (int num : nums) {
12. map.put(num, map.getOrDefault(num, 0) + 1);
13. }
14. System.out.println(map);
15. PriorityQueue<Integer> pq = new PriorityQueue<>(k, new Comparator<Integer>() {
16. @Override
17. public int compare(Integer o1, Integer o2) {
18. return map.get(o1) - map.get(o2);//不用造class来储存值和次数
19. }
20. });
21. for (int key : map.keySet()) {
22. if (pq.size() == k) {
23. if (map.get(pq.peek()) < map.get(key)) {
24. pq.poll();
25. pq.offer(key);
26. }
27. } else {
28. pq.offer(key);
29. }
30. }
31. while (!pq.isEmpty()) {
33. }
34. return result;
35. }
Read full article from Top k elements with most occurrences – Cracking Code