File tree Expand file tree Collapse file tree 1 file changed +11
-19
lines changed Expand file tree Collapse file tree 1 file changed +11
-19
lines changed Original file line number Diff line number Diff line change 1
1
class Solution {
2
2
public int minSetSize (int [] arr ) {
3
- Map <Integer , Integer > map = new HashMap <>();
4
- for (int num : arr ) {
5
- map .put (num , map .getOrDefault (num , 0 ) + 1 );
3
+ Map <Integer , Long > frequencyMap = Arrays .stream (arr ).boxed ()
4
+ .collect (Collectors .groupingBy (Function .identity (), HashMap ::new , Collectors .counting ()));
5
+ int halfSize = arr .length / 2 ;
6
+ PriorityQueue <Integer > pq = new PriorityQueue <>(
7
+ (o1 , o2 ) -> (int ) (frequencyMap .get (o2 ) - frequencyMap .get (o1 )));
8
+ pq .addAll (frequencyMap .keySet ());
9
+ int counter = 0 ;
10
+ while (!pq .isEmpty () && halfSize > 0 ) {
11
+ halfSize -= frequencyMap .get (pq .poll ());
12
+ counter ++;
6
13
}
7
- PriorityQueue <Integer > pq = new PriorityQueue <>(new Comparator <Integer >(){
8
- public int compare (Integer o1 , Integer o2 ) {
9
- return map .get (o2 ) - map .get (o1 );
10
- }
11
- });
12
- for (Integer key : map .keySet ()) {
13
- pq .add (key );
14
- }
15
- int n = arr .length / 2 ;
16
- int currSize = 0 ;
17
- int count = 0 ;
18
- while (currSize < n ) {
19
- currSize += map .get (pq .poll ());
20
- count ++;
21
- }
22
- return count ;
14
+ return counter ;
23
15
}
24
16
}
You can’t perform that action at this time.
0 commit comments