-
Notifications
You must be signed in to change notification settings - Fork 0
/
K_Frequent_Elements
37 lines (28 loc) · 1.16 KB
/
K_Frequent_Elements
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
# K frquent element
class Solution {
public int[] topKFrequent(int[] nums, int k) {
Map<Integer,Integer> map=new HashMap<>();
int result[]=new int[k];
for(int x:nums)
{
map.put(x,map.getOrDefault(x,0)+1);
}
List<Integer> list=new ArrayList<>(map.keySet());
Collections.sort(list,(a,b)->
map.get(b)-map.get(a));
// Arrays.sort(obj,-1);
for(int i=0;i<k;i++)
{ result[i]=list.get(i);
}
return result;
}
}
/*
Explaination:
(a,b) -> map.get(b) - map.get(a) is a lambda expression, Also known as a comparator.
It's defining the 'priority' of the queue to be whichever number ( a or b ) is bigger.
It works like this...
If (a,b) -> map.get(b) - map.get(a) - It will start adding elements with their freq in decreasing order (in this case, it will be 3 2 1 (freq))
if (a,b) -> map.get(a) - map.get(b) - It will start adding element with their freq in increasing order (in this case, it will be 1 2 3 (freq))
// Since you are always doing map.get, it means you're comparing it on values only, so doesn't confuse it with whatever is written in the key
*/