Skip to content

Commit e78a83d

Browse files
authored
Update 1982-find-array-given-subset-sums.js
1 parent d8312c0 commit e78a83d

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

1982-find-array-given-subset-sums.js

+48
Original file line numberDiff line numberDiff line change
@@ -41,3 +41,51 @@ function bs(arr, e) {
4141

4242
return arr[l] === e
4343
}
44+
45+
// another
46+
47+
/**
48+
* @param {number} n
49+
* @param {number[]} sums
50+
* @return {number[]}
51+
*/
52+
const recoverArray = function(n, sums) {
53+
const res = []
54+
sums.sort((a, b) => a - b)
55+
56+
while(res.length < n) {
57+
const visited = Array(sums.length).fill(false)
58+
const a1 = [], a2 = []
59+
const d = sums[1] - sums[0]
60+
for(let i = 0, j = 1; i < sums.length; i++, j++) {
61+
while(i < sums.length && visited[i]) i++
62+
if(i === sums.length) break
63+
while(j <= i || sums[j] !== sums[i] + d) j++
64+
a1.push(sums[i])
65+
a2.push(sums[j])
66+
visited[i] = visited[j] = true
67+
}
68+
69+
if(bs(a1, 0)) {
70+
sums = a1
71+
res.push(d)
72+
} else {
73+
sums = a2
74+
res.push(-d)
75+
}
76+
}
77+
78+
return res
79+
};
80+
81+
function bs(arr, val) {
82+
let l = 0, r = arr.length - 1
83+
while(l < r) {
84+
const mid = ~~((l + r) / 2)
85+
if(arr[mid] < val) l = mid + 1
86+
else r = mid
87+
}
88+
89+
return arr[l] === val
90+
}
91+

0 commit comments

Comments
 (0)