极客时间返利平台,你可以在上边通过山月的链接购买课程,并添加我的微信 (shanyue94) 领取返现。

# 如何在数组中找出三个数之和为 N

Issue

欢迎在 Gtihub Issue 中回答此问题: Issue 177 (opens new window)

Author

回答者: HNHED (opens new window)

排序之后使用双指针 let ar = [5, 12, 6, 3, 9, 2, 1, 7];

function getthreenum(arr, target, result = []) { arr = arr.sort((a, b) => a - b) const len = arr.length; for (let i = 0; i < len; i++) { let j = i + 1; let k = len - 1; while (j < k) { if (arr[j] + arr[k] > target - arr[i]) { k--; } else if (arr[j] + arr[k] < target - arr[i]) { j++; } else { result.push([arr[i], arr[j], arr[k]]); j++; } } } return result; } console.log(getthreenum(ar, 13, []));

Last Updated: 2/23/2022, 11:56:07 AM