Skip to content

Commit e7d98ae

Browse files
hashmap priorityqueue(max-heap) bucket sort medium good try array
Given an integer array nums and an integer k, return the k most frequent elements. You may return the answer in any order. Example 1: Input: nums = [1,1,1,2,2,3], k = 2 Output: [1,2] Example 2: Input: nums = [1], k = 1 Output: [1] Constraints: 1 <= nums.length <= 105 -104 <= nums[i] <= 104 k is in the range [1, the number of unique elements in the array]. It is guaranteed that the answer is unique. Follow up: Your algorithm's time complexity must be better than O(n log n), where n is the array's size. Seen this question in a real interview before? 1/5 Yes No Accepted 2.4M Submissions 3.8M Acceptance Rate 63.6% Topics Array Hash Table Divide and Conquer Sorting Heap (Priority Queue) Bucket Sort Counting Quickselect
1 parent 00e33af commit e7d98ae

File tree

1 file changed

+95
-0
lines changed

1 file changed

+95
-0
lines changed

top-k-frequent-elements.java

Lines changed: 95 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,95 @@
1+
class Solution {
2+
public int[] topKFrequent(int[] nums, int k) {
3+
Map<Integer, Integer> counter = new HashMap<>();
4+
for (int n : nums) {
5+
counter.put(n, counter.getOrDefault(n, 0) + 1);
6+
}
7+
8+
List<Integer>[] freq = new ArrayList[nums.length + 1];
9+
for (int i = 0; i < freq.length; i++) {
10+
freq[i] = new ArrayList<>();
11+
}
12+
/*An array of List<Integer> called freq is created with nums.length + 1 buckets.
13+
Each index i in freq represents a list of numbers that appear i times in nums.
14+
The length of nums + 1 ensures that we can represent frequencies from 0 to nums.length (the maximum possible frequency).*/
15+
16+
for (Map.Entry<Integer, Integer> entry : counter.entrySet()) {
17+
int frequency = entry.getValue();
18+
freq[frequency].add(entry.getKey());
19+
}
20+
//Populate the Bucket Array
21+
//Iterate over the entries in the counter map. For each entry, add the key (the number) to the list at the index corresponding to its frequency in freq.
22+
23+
int[] res = new int[k];
24+
int idx = 0;
25+
for (int i = freq.length - 1; i >= 0; i--) {
26+
for (int num : freq[i]) {
27+
res[idx++] = num;
28+
if (idx == k) {
29+
return res;
30+
}
31+
}
32+
}
33+
/* Start iterating from the end of freq (the highest possible frequency) down to 0.
34+
For each non-empty bucket, add the elements to res until k elements have been collected.
35+
If idx reaches k, return the res array. */
36+
37+
return new int[0];
38+
}
39+
}
40+
41+
42+
43+
44+
45+
class Solution {
46+
public int[] topKFrequent(int[] nums, int k) {
47+
Map<Integer, Integer> counter = new HashMap<>();
48+
for (int n : nums) {
49+
counter.put(n, counter.getOrDefault(n, 0) + 1);
50+
}
51+
52+
PriorityQueue<Map.Entry<Integer, Integer>> heap = new PriorityQueue<>(
53+
(a, b) -> Integer.compare(b.getValue(), a.getValue())
54+
);
55+
//A PriorityQueue named heap is created to act as a max heap based on the frequency of the elements.
56+
//The comparator (a, b) -> Integer.compare(b.getValue(), a.getValue()) ensures that entries with higher frequencies are given higher priority, making it a max heap.
57+
58+
for (Map.Entry<Integer, Integer> entry : counter.entrySet()) {
59+
heap.offer(entry);
60+
}
61+
//Each entry from the counter map is added to the heap. The heap will order the entries such that the element with the highest frequency is at the top.
62+
63+
int[] res = new int[k];
64+
for (int i = 0; i < k; i++) {
65+
res[i] = Objects.requireNonNull(heap.poll()).getKey();
66+
}
67+
//The heap.poll() method retrieves and removes the element at the top of the heap (i.e., the element with the highest frequency). The getKey() method extracts the number, which is added to res.
68+
//Objects.requireNonNull() ensures that poll() does not return null, adding a layer of safety.
69+
return res;
70+
}
71+
}
72+
73+
74+
75+
76+
class Solution {
77+
public int[] topKFrequent(int[] nums, int k) {
78+
Map<Integer, Integer> frequencyMap = new HashMap<>();
79+
80+
for (int n : nums) {
81+
frequencyMap.put(n, frequencyMap.getOrDefault(n, 0) + 1);
82+
}
83+
84+
List<Map.Entry<Integer, Integer>> entryList = new ArrayList<>(frequencyMap.entrySet());
85+
86+
Collections.sort(entryList, (a, b) -> b.getValue()- a.getValue());
87+
88+
int[] result = new int[k];
89+
for (int i = 0; i < k; i++) {
90+
result[i] = entryList.get(i).getKey();
91+
}
92+
93+
return result;
94+
}
95+
}

0 commit comments

Comments
 (0)