Skip to content

Commit 7aedc04

Browse files
committed
issue sowon-dev#27 Missing Numbers java w/ Explanation
1 parent 590b43d commit 7aedc04

1 file changed

Lines changed: 56 additions & 0 deletions

File tree

‎src/hackerrank/MissingNumbers.java‎

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
package hackerrank;
2+
3+
import java.util.ArrayList;
4+
import java.util.Arrays;
5+
import java.util.HashMap;
6+
7+
public class MissingNumbers {
8+
9+
static int[] missingNumbers(int[] arr, int[] brr) {
10+
//arr과 brr을 비교하여 brr에는 있지만 arr에는 없는 숫자(Missing Numbers)를 배열로 나타내는 문제.
11+
//두 배열을 각각 HashMap에 담은 뒤 brr 해쉬맵 - arr 해쉬맵을 통해 빠진 숫자를 효율적으로 찾을 수 있다.
12+
HashMap<Integer, Integer> hashmapA = new HashMap<Integer, Integer>();
13+
HashMap<Integer, Integer> hashmapB = new HashMap<Integer, Integer>();
14+
15+
//arr을 HashMap으로 만든 뒤 반복되는 숫자가 있으면 value값을 1 누적합한다.
16+
for (int i : arr) {
17+
if (hashmapA.containsKey(i)) {
18+
hashmapA.put(i, hashmapA.get(i) + 1);
19+
} else {
20+
hashmapA.put(i, 1);
21+
}
22+
}
23+
24+
//brr을 HashMap으로 만든 뒤 반복되는 숫자가 있으면 value값을 1 누적합한다.
25+
for (int j : brr) {
26+
if (hashmapB.containsKey(j)) {
27+
hashmapB.put(j, hashmapB.get(j) + 1);
28+
} else {
29+
hashmapB.put(j, 1);
30+
}
31+
}
32+
33+
//HashMapB - HashMapA한 값을 리스트 diff에 담는다.
34+
ArrayList<Integer> diff = new ArrayList<Integer>();
35+
for (Integer i : hashmapB.keySet()) {
36+
if (hashmapA.get(i) == null || hashmapA.get(i) < hashmapB.get(i)) {
37+
diff.add(i);
38+
}
39+
}
40+
41+
//리스트를 배열로 만든다.
42+
int[] result = new int[diff.size()];
43+
for (int i = 0; i < diff.size(); i++) {
44+
result[i] = diff.get(i);
45+
}
46+
47+
System.out.println(Arrays.toString(result));
48+
return result;
49+
}
50+
51+
public static void main(String[] args) {
52+
System.out.println(missingNumbers(new int[]{203, 204, 205, 206, 207, 208, 203, 204, 205, 206},
53+
new int[]{203, 204, 204, 205, 206, 207, 205, 208, 203, 206, 205, 206, 204})
54+
+ ", ans: [204 205 206]");
55+
}
56+
}

0 commit comments

Comments
 (0)