Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commitef904be

Browse files
add a solution for 1338
1 parent37b806b commitef904be

File tree

1 file changed

+24
-35
lines changed

1 file changed

+24
-35
lines changed

‎src/main/java/com/fishercoder/solutions/_1338.java

Lines changed: 24 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -6,41 +6,6 @@
66
importjava.util.List;
77
importjava.util.Map;
88

9-
/**
10-
* 1338. Reduce Array Size to The Half
11-
*
12-
* Given an array arr. You can choose a set of integers and remove all the occurrences of these integers in the array.
13-
* Return the minimum size of the set so that at least half of the integers of the array are removed.
14-
*
15-
* Example 1:
16-
* Input: arr = [3,3,3,3,5,5,5,2,2,7]
17-
* Output: 2
18-
* Explanation: Choosing {3,7} will make the new array [5,5,5,2,2] which has size 5 (i.e equal to half of the size of the old array).
19-
* Possible sets of size 2 are {3,5},{3,2},{5,2}.
20-
* Choosing set {2,7} is not possible as it will make the new array [3,3,3,3,5,5,5] which has size greater than half of the size of the old array.
21-
*
22-
* Example 2:
23-
* Input: arr = [7,7,7,7,7,7]
24-
* Output: 1
25-
* Explanation: The only possible set you can choose is {7}. This will make the new array empty.
26-
*
27-
* Example 3:
28-
* Input: arr = [1,9]
29-
* Output: 1
30-
*
31-
* Example 4:
32-
* Input: arr = [1000,1000,3,7]
33-
* Output: 1
34-
*
35-
* Example 5:
36-
* Input: arr = [1,2,3,4,5,6,7,8,9,10]
37-
* Output: 5
38-
*
39-
* Constraints:
40-
* 1 <= arr.length <= 10^5
41-
* arr.length is even.
42-
* 1 <= arr[i] <= 10^5
43-
* */
449
publicclass_1338 {
4510
publicstaticclassSolution1 {
4611
publicintminSetSize(int[]arr) {
@@ -61,4 +26,28 @@ public int minSetSize(int[] arr) {
6126
returni--;
6227
}
6328
}
29+
30+
publicstaticclassSolution2 {
31+
publicintminSetSize(int[]arr) {
32+
Map<Integer,Integer>map =newHashMap<>();
33+
for (intnum :arr) {
34+
map.put(num,map.getOrDefault(num,0) +1);
35+
}
36+
List<int[]>list =newArrayList<>();
37+
for (intkey :map.keySet()) {
38+
list.add(newint[]{map.get(key),key});
39+
}
40+
Collections.sort(list, (a,b) ->b[0] -a[0]);
41+
intminSet =0;
42+
intcount =0;
43+
for (int[]pair :list) {
44+
count +=pair[0];
45+
minSet++;
46+
if (count >=arr.length /2) {
47+
returnminSet;
48+
}
49+
}
50+
returnminSet;
51+
}
52+
}
6453
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp