Advertisement
exmkg

Untitled

Aug 23rd, 2024
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.54 KB | None | 0 0
  1. class Solution {
  2.     public int[] topKFrequent(int[] nums, int k) {
  3.         // Map<Number, Frequency>
  4.         Map<Integer, Integer> freq = new HashMap<>();
  5.  
  6.         // First, count for each number its frequency.
  7.         for (int x : nums) {
  8.             freq.put(x, freq.getOrDefault(x, 0) + 1);
  9.         }
  10.  
  11.         //                                                 (key  ,   value)
  12.         // Convert the Map<Number, Frequency> to List<Pair<Number, Frequency>>.
  13.         List<Pair<Integer, Integer>> sorted_freq_pairs = new ArrayList<>();
  14.         for (var entry : freq.entrySet()) {
  15.             Pair<Integer, Integer> freq_pair = new Pair<>(entry.getKey(), entry.getValue());
  16.             sorted_freq_pairs.add(freq_pair);
  17.         }
  18.  
  19.         // T: O(n log n)
  20.         // S: O(n)
  21.  
  22.         //                (key  ,   value)
  23.         // Sort List<Pair<Number, Frequency>> by the Frequency (i.e. value)
  24.         // in descending order.
  25.         Collections.sort(sorted_freq_pairs, (fp1, fp2) -> {
  26.             // < 0
  27.             // == 0
  28.             // > 0
  29.             return fp2.getValue() - fp1.getValue();
  30.         });
  31.  
  32.         // Create array to save k most frequent numbers.
  33.         int[] results = new int[k];
  34.         for (int i = 0; i < k; i++) {
  35.             //      (key   , value   )
  36.             // Now, (Number, Frequency) pairs are sorted in descending order.
  37.             // Get the first k Numbers (i.e. keys) and save them in results.
  38.             results[i] = sorted_freq_pairs.get(i).getKey();
  39.         }
  40.         return results;
  41.     }
  42. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement