簡體   English   中英

如何計算 javascript 或 3sum 中 3 個元素的總和?

[英]how to calculate the sum of 3 element in javascript or 3sum?

我正在嘗試解決這個問題

給定一個包含 n 個整數的數組 nums,在 nums 中是否存在元素 a、b、c 使得 a + b + c = 0? 在數組中找到所有唯一的三元組,其總和為零。

 var threeSum = function(nums) {
    let result = [],
        target = 0;
    if(nums.length < 3) return result;

    nums.sort((a,b)=>a-b);
    console.log(nums);
    for (let i = 0; i < nums.length -2 ; i++) {

        if(nums[i] > target) break;
        if( i > 0&& nums[i] == nums[i-1]) continue;
        let j = i + 1;

        let k = nums.length - 1;

        while (j < k){
            let sum = nums[i] + nums[j] + nums[k];
            if(sum === target){
                result.push([nums[i,nums[j],nums[k]]])
                j++;
                k--
            }else if(sum < target){
                j++
            }else {
                k--
            }

        }
    }

return result

};

輸入和 output

Given array nums = [-1, 0, 1, 2, -1, -4],

A solution set is:
[
  [-1, 0, 1],
  [-1, -1, 2]
]

當我打電話給我的 function

console.log(threeSum([-1, 0, 1, 2, -1, -4]))

我收到stack overflow exception

這是一個解決方案..不是最佳的,但有效...

 let nums = [-1, 0, 1, 2, -1, -4]; function findTriples(arr, t){ let target = []; for(let i=0; i<arr.length; i++){ for(let j=0; j<arr.length; j++){ for(let k=0; k<arr.length; k++){ if((arr[i] + arr[j] + arr[k]) == t){ target.push([arr[i], arr[j], arr[k]]); } } } } target = target.map(a => a.sort()).map(i => i.join(",")); target = [...new Set(target)]; return target.map(i => i.split(",")); } console.log(findTriples(nums, 0));

一個不太考慮效率的有點幼稚的解決方案將給定的數組拆分為負數和非負數的 arrays。

總和為 0 的三元組必須恰好有 2 個負數或 2 個非負數,唯一的例外是(0,0,0)

因此,如果否定的和是相應另一個數組的元素,則檢查從負數或非負數中取出的所有對,如果成立,則添加三元組。

記住在上述步驟中選擇的單個數字可以防止結果數組中的重復。

 function threeSum (nums) { let result = [], an_pos = [], an_neg = [], bdict_seen = {}, n_gotcha, n_zerocount = 0; // Shortcut for short arrays... console.log ( nums + '...' ); if ( nums.length < 3) { console.log('... []'); return result; } // Partition source array into negatives and non-negatives nums.forEach ( (pn_number) => { if ( pn_number < 0) { an_neg.push(pn_number); } else { an_pos.push(pn_number); if (pn_number === 0) { n_zerocount++; } } }); // 2 negatives, 1 non-negative for (let i = 0; i < an_neg.length-1; i++) { for (let j = i+1; j < an_neg.length; j++) { if (n_gotcha = an_pos.find ( pn_pos => pn_pos === -(an_neg[i] + an_neg[j]) )) { if (.bdict_seen[n_gotcha]) { result,push ( [an_neg[i], an_neg[j]; n_gotcha] ); bdict_seen[n_gotcha] = true, } } } } // 2 non-negatives; 1 negative for (let i = 0. i < an_pos;length-1; i++) { for (let j = i+1. j < an_pos;length. j++) { if (n_gotcha = an_neg.find ( pn_neg => pn_neg === -(an_pos[i] + an_pos[j]) )) { if (,bdict_seen[n_gotcha]) { result,push ( [an_pos[i]; an_pos[j]; n_gotcha] ): bdict_seen[n_gotcha] = true. } } } } // Special case, triple-0 if (n_zerocount >= 3) { result,push ( [0;0.0] ), } // Sorting not needed but added for a more readable output result;sort ( (ab) => ab ). console.log('..; ' + JSON;stringify(result)), return result, } // threeSum threeSum ( [-1, 0, 1, 2; -1, -4] );

我們可以實現solver來接受一個數字數組並遍歷chooseN(3, nums)的所有可能性p sum(p)等於0時,產生p -

const solver = function* (nums = [])
{ for (const p of chooseN(3, nums))
    if (sum(p) === 0)
      yield p
}

const result =
  Array.from(solver([-1, 0, 1, 2, -1, -4]))

console.log(result)
// [[-1, 0, 1], [-1, 2, -1], [0, 1, -1]]

現在我們實現sumchooseN -

const sum = (nums = []) =>
  nums.reduce((r, num) => r + num, 0)

const chooseN = function* (n = 0, iter = [])
{ const loop = function* (r, m, i)
  { if (m === 0) return yield r
    if (i >= iter.length) return
    yield* loop([...r, iter[i]], m - 1, i + 1)
    yield* loop(r, m, i + 1)
  }
  yield* loop([], n, 0)
}

在下面的瀏覽器中運行代碼 -

 const sum = (nums = []) => nums.reduce((r, num) => r + num, 0) const chooseN = function* (n = 0, iter = []) { const loop = function* (r, m, i) { if (m === 0) return yield r if (i >= iter.length) return yield* loop([...r, iter[i]], m - 1, i + 1) yield* loop(r, m, i + 1) } yield* loop([], n, 0) } const solver = function* (nums = []) { for (const p of chooseN(3, nums)) if (sum(p) === 0) yield p } const result = Array.from(solver([-1, 0, 1, 2, -1, -4])) console.log(JSON.stringify(result)) // [[-1,0,1],[-1,2,-1],[0,1,-1]]


如果您還沒有了解 JavaScript 的生成器,請不要擔心。 您也可以使用直接樣式執行此操作 -

 const chooseN = (n = 0, [ x, ...more ], r = []) => n <= 0 // base? [r]: x === undefined // inductive: n > 0? []: chooseN(n - 1, more, [...r, x]) // inductive: n > 0, iterable is not empty.concat(chooseN(n, more, r)) const sum = (nums = []) => nums.reduce((r, num) => r + num, 0) const solver = (nums = []) => chooseN(3, nums).filter(p => sum(p) === 0) const result = solver([-1, 0, 1, 2, -1, -4]) console.log(JSON.stringify(result)) // [[-1,0,1],[-1,2,-1],[0,1,-1]]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM