-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathMissingNumbers.java
More file actions
56 lines (47 loc) ยท 1.87 KB
/
Copy pathMissingNumbers.java
File metadata and controls
56 lines (47 loc) ยท 1.87 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package hackerrank;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
public class MissingNumbers {
static int[] missingNumbers(int[] arr, int[] brr) {
//arr๊ณผ brr์ ๋น๊ตํ์ฌ brr์๋ ์์ง๋ง arr์๋ ์๋ ์ซ์(Missing Numbers)๋ฅผ ๋ฐฐ์ด๋ก ๋ํ๋ด๋ ๋ฌธ์ .
//๋ ๋ฐฐ์ด์ ๊ฐ๊ฐ HashMap์ ๋ด์ ๋ค brr ํด์ฌ๋งต - arr ํด์ฌ๋งต์ ํตํด ๋น ์ง ์ซ์๋ฅผ ํจ์จ์ ์ผ๋ก ์ฐพ์ ์ ์๋ค.
HashMap<Integer, Integer> hashmapA = new HashMap<Integer, Integer>();
HashMap<Integer, Integer> hashmapB = new HashMap<Integer, Integer>();
//arr์ HashMap์ผ๋ก ๋ง๋ ๋ค ๋ฐ๋ณต๋๋ ์ซ์๊ฐ ์์ผ๋ฉด value๊ฐ์ 1 ๋์ ํฉํ๋ค.
for (int i : arr) {
if (hashmapA.containsKey(i)) {
hashmapA.put(i, hashmapA.get(i) + 1);
} else {
hashmapA.put(i, 1);
}
}
//brr์ HashMap์ผ๋ก ๋ง๋ ๋ค ๋ฐ๋ณต๋๋ ์ซ์๊ฐ ์์ผ๋ฉด value๊ฐ์ 1 ๋์ ํฉํ๋ค.
for (int j : brr) {
if (hashmapB.containsKey(j)) {
hashmapB.put(j, hashmapB.get(j) + 1);
} else {
hashmapB.put(j, 1);
}
}
//HashMapB - HashMapAํ ๊ฐ์ ๋ฆฌ์คํธ diff์ ๋ด๋๋ค.
ArrayList<Integer> diff = new ArrayList<Integer>();
for (Integer i : hashmapB.keySet()) {
if (hashmapA.get(i) == null || hashmapA.get(i) < hashmapB.get(i)) {
diff.add(i);
}
}
//๋ฆฌ์คํธ๋ฅผ ๋ฐฐ์ด๋ก ๋ง๋ ๋ค.
int[] result = new int[diff.size()];
for (int i = 0; i < diff.size(); i++) {
result[i] = diff.get(i);
}
System.out.println(Arrays.toString(result));
return result;
}
public static void main(String[] args) {
System.out.println(missingNumbers(new int[]{203, 204, 205, 206, 207, 208, 203, 204, 205, 206},
new int[]{203, 204, 204, 205, 206, 207, 205, 208, 203, 206, 205, 206, 204})
+ ", ans: [204 205 206]");
}
}