11import java .util .*;
22
3- class Solution {
3+ // Time complexity: O(Nlogk)
4+ // Space complexity: O(N)
5+ class Solution1 {
46 // return: top k most freq elements
57 public int [] topKFrequent (int [] nums , int k ) {
68 HashMap <Integer , Integer > freq = new HashMap <>();
@@ -27,3 +29,39 @@ public int[] topKFrequent(int[] nums, int k) {
2729 return result ;
2830 }
2931}
32+
33+ // Time complexity: O(N)
34+ // Space complexity: O(N)
35+ class Solution2 {
36+ public int [] topKFrequent (int [] nums , int k ) {
37+ // count frequencies
38+ Map <Integer , Integer > freq = new HashMap <>();
39+ for (int num : nums ) {
40+ freq .put (num , freq .getOrDefault (num , 0 ) + 1 );
41+ }
42+
43+ // bucket: index = frequency, value = list of numbers
44+ List <List <Integer >> buckets = new ArrayList <>(nums .length + 1 );
45+ for (int i = 0 ; i <= nums .length ; i ++) {
46+ buckets .add (new ArrayList <>());
47+ }
48+
49+ for (var entry : freq .entrySet ()) {
50+ int num = entry .getKey ();
51+ int count = entry .getValue ();
52+ buckets .get (count ).add (num );
53+ }
54+
55+ // gather top k frequent elements
56+ int [] result = new int [k ];
57+ int idx = 0 ;
58+ for (int i = nums .length ; i >= 0 && idx < k ; i --) {
59+ for (int num : buckets .get (i )) {
60+ result [idx ++] = num ;
61+ if (idx == k ) break ;
62+ }
63+ }
64+
65+ return result ;
66+ }
67+ }
0 commit comments