Skip to content

Commit 13ea9ab

Browse files
authored
Create 2007-find-original-array-from-doubled-array.js
1 parent 78d3926 commit 13ea9ab

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
/**
2+
* @param {number[]} changed
3+
* @return {number[]}
4+
*/
5+
const findOriginalArray = function(changed) {
6+
const n = changed.length, res = []
7+
if(n % 2 === 1 || n === 0) return res
8+
const hash = {}
9+
for(let e of changed) {
10+
if(hash[e] == null) hash[e] = 0
11+
hash[e]++
12+
}
13+
changed.sort((a, b) => a - b)
14+
15+
for(let i = 0, len = n; i < len; i++) {
16+
const cur = changed[i], dVal = cur * 2
17+
if (cur === 0 && hash[cur] % 2 === 1) continue
18+
if(hash[dVal] && hash[cur]) {
19+
res.push(cur)
20+
hash[dVal]--
21+
hash[cur]--
22+
}
23+
}
24+
return res.length === n / 2 ? res : []
25+
};

0 commit comments

Comments
 (0)