Algorithms: Pairwise
This commit is contained in:
parent
96a5e6bff1
commit
3e3dce5f4a
30
Algorithms/pairwise.js
Normal file
30
Algorithms/pairwise.js
Normal file
@ -0,0 +1,30 @@
|
||||
// https://www.freecodecamp.org/learn/coding-interview-prep/algorithms/pairwise
|
||||
|
||||
function pairwise(arr, sum) {
|
||||
const arr2 = arr.map((num, index) => ({ num: num, index: index }));
|
||||
arr2.sort(({ num: numA, index: indexA }, { num: numB, index: indexB }) => {
|
||||
if (numA === numB) {
|
||||
return indexA - indexB;
|
||||
} else {
|
||||
return numA - numB;
|
||||
}
|
||||
});
|
||||
|
||||
let [i, reverseI, pairsIndexSum] = [0, arr2.length - 1, 0];
|
||||
while (i < reverseI) {
|
||||
if (arr2[i].num + arr2[reverseI].num === sum) {
|
||||
if (arr2[i].num === arr2[reverseI].num) {
|
||||
pairsIndexSum += arr2[i++].index + arr2[i++].index;
|
||||
} else {
|
||||
pairsIndexSum += arr2[i++].index + arr2[reverseI--].index;
|
||||
}
|
||||
} else if (arr2[i].num + arr2[reverseI].num < sum) {
|
||||
i++;
|
||||
} else {
|
||||
reverseI--;
|
||||
}
|
||||
}
|
||||
return pairsIndexSum;
|
||||
}
|
||||
|
||||
console.log(pairwise([1, 1, 1], 2));
|
Loading…
Reference in New Issue
Block a user