-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDay_49.java
More file actions
43 lines (39 loc) · 1.08 KB
/
Copy pathDay_49.java
File metadata and controls
43 lines (39 loc) · 1.08 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
// Top K Frequent Elements
class Solution {
public int[] topKFrequent(int[] nums, int k) {
int n = nums.length;
int[] ans = new int[k];
Map<Integer,Integer> mpp = new HashMap<>();
for(int i=0;i<n;i++){
mpp.put(nums[i],mpp.getOrDefault(nums[i],0)+1);
}
PriorityQueue<Integer> pq = new PriorityQueue<>((a,b) -> Integer.compare(mpp.get(b),mpp.get(a)));
for(var it : mpp.keySet()){
pq.offer(it);
}
int i = 0;
while(i<k && !pq.isEmpty()){
ans[i] = pq.poll();
i++;
}
return ans;
}
}
// Kth Largest Element in an Array
class Solution {
public int findKthLargest(int[] nums, int k) {
int n = nums.length;
PriorityQueue<Integer> pq = new PriorityQueue<>();
for(int i=0;i<k;i++){
pq.offer(nums[i]);
}
for(int i=k;i<n;i++){
int val = nums[i];
if(val>pq.peek()){
pq.poll();
pq.offer(val);
}
}
return pq.peek();
}
}