Skip to content

Commit 962882e

Browse files
authored
Create Find Original Array From Doubled Array.java
1 parent 1a1c149 commit 962882e

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
class Solution {
2+
public int[] findOriginalArray(int[] changed) {
3+
if (changed.length % 2 != 0) {
4+
return new int[]{};
5+
}
6+
int[] answer = new int[changed.length / 2];
7+
int idx = 0;
8+
Map<Integer, Long> map = Arrays.stream(changed).boxed()
9+
.collect(Collectors.groupingBy(Function.identity(), TreeMap::new, Collectors.counting()));
10+
for (Integer key : map.keySet()) {
11+
if (map.get(key) > map.getOrDefault(key * 2, 0L)) {
12+
return new int[0];
13+
}
14+
for (int i = 0; i < map.get(key); i++) {
15+
answer[idx++] = key;
16+
map.put(key * 2, map.get(key * 2) - 1);
17+
}
18+
}
19+
return answer;
20+
}
21+
}

0 commit comments

Comments
 (0)