Skip to content

Commit 73f28c6

Browse files
authored
Update Reduce Array Size to The Half.java
1 parent 42361da commit 73f28c6

File tree

1 file changed

+11
-19
lines changed

1 file changed

+11
-19
lines changed
Lines changed: 11 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,16 @@
11
class Solution {
22
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++;
613
}
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;
2315
}
2416
}

0 commit comments

Comments
 (0)