Skip to content

Commit d8873a6

Browse files
authored
Create 2122-recover-the-original-array.js
1 parent d662367 commit d8873a6

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

2122-recover-the-original-array.js

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
/**
2+
* @param {number[]} nums
3+
* @return {number[]}
4+
*/
5+
const recoverArray = function(nums) {
6+
const n = nums.length, cnt = calcHash(nums)
7+
nums.sort((a, b) => a - b)
8+
for(let i = 1; i < n; i++) {
9+
const tk = nums[i] - nums[0]
10+
if(tk === 0 || tk % 2 === 1) continue
11+
const [valid, res] = helper(tk)
12+
if(valid) return res
13+
}
14+
15+
function helper(tk) {
16+
const res = [], hash = Object.assign({}, cnt)
17+
for(let i = 0; i < n; i++) {
18+
const cur = nums[i]
19+
if(hash[cur] === 0) continue
20+
if(hash[cur + tk] === 0 || hash[cur + tk] == null) return [false]
21+
hash[cur]--
22+
hash[cur + tk]--
23+
res.push(cur + tk / 2)
24+
}
25+
return [true, res]
26+
}
27+
function calcHash(arr) {
28+
const hash = {}
29+
for(let e of arr) {
30+
if(hash[e] == null) hash[e] = 0
31+
hash[e]++
32+
}
33+
return hash
34+
}
35+
};

0 commit comments

Comments
 (0)