공부기록

347. Top K Frequent Elements 본문

코테/LeetCode

347. Top K Frequent Elements

코타쿠 2022. 4. 16. 10:10

문제

https://leetcode.com/problems/top-k-frequent-elements/

코드

import java.util.*;

class Solution {

    class Node implements Comparable<Node>{
        int num;
        int count;

        public Node(int num, int count){
            this.num = num;
            this.count = count;
        }

        @Override
        public int compareTo(Node n){
            if(this.count < n.count)
                return 1;
            else if(this.count == n.count)
                return 0;
            return -1;
        }

    }

    public int[] topKFrequent(int[] nums, int k) {
        List<Integer> res = new ArrayList<>();
        Map<Integer, Integer> m = new HashMap<>();
        PriorityQueue<Node> pq = new PriorityQueue<>();

        for(int num : nums){
            if(m.get(num) == null)
                m.put(num, 0);
            m.replace(num, m.get(num)+1);
        }

        for(int key : m.keySet()){
            pq.add(new Node(key, m.get(key)));
        }

        while(k-- != 0){
            res.add(pq.poll().num);
        }

        return res.stream().mapToInt(Integer::intValue).toArray();
    }
}

피드백

'코테 > LeetCode' 카테고리의 다른 글

74. Search a 2D Matrix  (0) 2022.04.21
49. Group Anagrams  (0) 2022.04.19
179. Largest Number  (0) 2022.04.15
384. Shuffle an Array  (0) 2022.04.09
210. Course Schedule II  (0) 2022.04.08