Skip to content

Commit 4adc51f

Browse files
authored
2022-08-18 update: added "Reduce Array Size to The Half" (#70)
1 parent d11a15a commit 4adc51f

File tree

2 files changed

+53
-0
lines changed

2 files changed

+53
-0
lines changed
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
package com.smlnskgmail.jaman.leetcodejava.medium;
2+
3+
import java.util.*;
4+
5+
// https://leetcode.com/problems/reduce-array-size-to-the-half/
6+
public class ReduceArraySizeToTheHalf {
7+
8+
private final int[] input;
9+
10+
public ReduceArraySizeToTheHalf(int[] input) {
11+
this.input = input;
12+
}
13+
14+
public int solution() {
15+
int n = input.length;
16+
if (n < 3) {
17+
return 1;
18+
}
19+
Map<Integer, Integer> m = new HashMap<>();
20+
for (int num : input) {
21+
m.put(num, m.getOrDefault(num, 0) + 1);
22+
}
23+
Queue<Integer> q = new PriorityQueue<>(Collections.reverseOrder());
24+
for (int num : m.values()) {
25+
q.offer(num);
26+
}
27+
int r = 0;
28+
int result = 0;
29+
while (r < n / 2 && q.size() > 0) {
30+
r += q.poll();
31+
result++;
32+
}
33+
return result;
34+
}
35+
36+
}
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
package com.smlnskgmail.jaman.leetcodejava.medium;
2+
3+
import org.junit.Test;
4+
5+
import static org.junit.Assert.assertEquals;
6+
7+
public class ReduceArraySizeToTheHalfTest {
8+
9+
@Test
10+
public void defaultTest() {
11+
assertEquals(
12+
2,
13+
new ReduceArraySizeToTheHalf(new int[]{3, 3, 3, 3, 5, 5, 5, 2, 2, 7}).solution()
14+
);
15+
}
16+
17+
}

0 commit comments

Comments
 (0)