-
347. Top K Frequent ElementsAlgorithm/java tip 2021. 3. 24. 00:42
leetcode.com/problems/top-k-frequent-elements/
class Solution { /** 1. priority queue 2. array and sort */ public int[] topKFrequent(int[] nums, int k) { // {num : cnt} Map<Integer, Integer> map = new HashMap<Integer, Integer>(); for(int num : nums) { if(map.containsKey(num)) { map.put(num, map.get(num) + 1); } else { map.put(num, 1); } } PriorityQueue<Data> pq = new PriorityQueue<>(k, (a, b) -> b.cnt - a.cnt); for(Map.Entry<Integer, Integer> e : map.entrySet()) { pq.offer(new Data(e.getKey(), e.getValue())); } int[] ans = new int[k]; for(int i=0; i<k; i++) { ans[i] = pq.poll().val; } return ans; } class Data { public int val; public int cnt; public Data(int val, int cnt) { this.val = val; this.cnt = cnt; } } }
'Algorithm > java tip' 카테고리의 다른 글
238. Product of Array Except Self (0) 2021.03.24 230. Kth Smallest Element in a BST (0) 2021.03.24 198. House Robber (0) 2021.03.23 1387. Sort Integers by The Power Value (0) 2021.03.21 1557. Minimum Number of Vertices to Reach All Nodes (0) 2021.03.20