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

2022-05-28T13:07:25

排序之后使用双指针 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, []));
当前页面是本站的「Baidu MIP」版。发表评论请点击:完整版 »