Skip to content

Commit c36c73d

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

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

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

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -89,3 +89,46 @@ function bs(arr, val) {
8989
return arr[l] === val
9090
}
9191

92+
// another
93+
94+
/**
95+
* @param {number} n
96+
* @param {number[]} sums
97+
* @return {number[]}
98+
*/
99+
const recoverArray = function(n, sums) {
100+
const res = []
101+
sums.sort((a, b) => a - b)
102+
103+
while(res.length < n) {
104+
const m = sums.length, visited = Array(m).fill(false)
105+
let a1 = [], a2 = [], delta = sums[1] - sums[0]
106+
for(let i = 0, j = 1; i < m && j < m; i++, j++) {
107+
while(i < m && visited[i]) i++
108+
if(i === m) break
109+
while(i >= j || sums[j] !== sums[i] + delta) j++
110+
if(j === m) break
111+
a1.push(sums[i])
112+
a2.push(sums[j])
113+
visited[i] = visited[j] = true
114+
}
115+
if(binarySearch(a1, 0)) {
116+
sums = a1
117+
res.push(delta)
118+
} else {
119+
sums = a2
120+
res.push(-delta)
121+
}
122+
}
123+
return res
124+
125+
function binarySearch(arr, val) {
126+
let l = 0, r = arr.length - 1
127+
while(l < r) {
128+
const mid = ~~((l + r) / 2)
129+
if(arr[mid] < val) l = mid + 1
130+
else r = mid
131+
}
132+
return arr[l] === val
133+
}
134+
};

0 commit comments

Comments
 (0)