titan2400

Top K Frequent Elements - LeetCode

Oct 24th, 2025
309
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.97 KB | Source Code | 0 0
  1. // Top K Frequent Elements - https://leetcode.com/problems/top-k-frequent-elements/description/?source=submission-ac
  2.  
  3. class Solution {
  4.  
  5.     // Time Complexity: O(nlogn)
  6.     public int[] topKFrequent(int[] nums, int k) {
  7.         Map<Integer, Integer> map = new HashMap<>();
  8.  
  9.         for (int i = 0; i < nums.length; i++) {
  10.             int count = map.getOrDefault(nums[i], 0);
  11.             map.put(nums[i], count + 1);
  12.         }
  13.  
  14.         // Sorted in descending order by count
  15.         PriorityQueue<Element> pq = new PriorityQueue<>(
  16.             (el1, el2) -> Integer.compare(el2.j, el1.j)
  17.         );
  18.  
  19.         for(Map.Entry<Integer, Integer> entry: map.entrySet()) {
  20.             System.out.println(entry.getKey() + " " + entry.getValue());
  21.             pq.offer(new Element(entry.getKey(), entry.getValue()));
  22.         }
  23.  
  24.         int[] result = new int[k];
  25.         for (int i = 0; i < k && !pq.isEmpty(); i++) {
  26.             Element el = pq.poll();
  27.             result[i] = el.i;
  28.         }
  29.  
  30.         return result;
  31.     }
  32.  
  33.     class Element {
  34.         int i, j;
  35.  
  36.         Element(int i, int j) {
  37.             this.i = i;
  38.             this.j = j;
  39.         }
  40.     }
  41.  
  42.     Time Complexity: O(Nlogk)
  43.     Space Complexity: O(N + k)
  44.     public int[] topKFrequent(int[] nums, int k) {
  45.         Map<Integer, Integer> count = new HashMap<>();
  46.  
  47.         for (int n: nums) {
  48.             count.put(n, count.getOrDefault(n, 0) + 1);
  49.         }
  50.  
  51.         // Sorted in descending order by count
  52.         Queue<Integer> minHeap = new PriorityQueue<>(
  53.             (n1, n2) ->
  54.                 Integer.compare(count.get(n1),
  55.                     count.get(n2))
  56.         );
  57.  
  58.         for(int n: count.keySet()) {
  59.             minHeap.offer(n);
  60.             if(minHeap.size() > k) {
  61.                 minHeap.poll();
  62.             }
  63.         }
  64.  
  65.         int[] top = new int[k];
  66.         for (int i = k - 1; i >= 0; i--) {
  67.             top[i] = minHeap.poll();
  68.         }
  69.  
  70.         return top;
  71.     }
  72. }
Advertisement
Add Comment
Please, Sign In to add comment