簡體   English   中英

獲取 javascript 中總和為 0 的所有子數組?

[英]get all subarray which have sum 0 in javascript?

我正在嘗試獲取 javascript 中總和為 0 的所有子數組? 我可以像這樣在O(n^2)中做到這一點

function getSubArray(input){

    let result =[]
    sum= 0
    let a = [];
    for(var i =0;i<input.length;i++){
        a=[];
        sum =0 ;
        for (let j = i; j < input.length; j++) {
            a.push(input[j])
            sum+=input[j];
            if(sum ===0){
                result.push(a);
            }
        }

    }

    return result

}

當我在 function console.log(getSubArray([1, 2, -3, 0, 4, -5, 2, -1]))上面調用時,它會打印在所有子數組中,但在O(n^2)中。

我嘗試使用 map 在O(n)中對此持樂觀態度

function getSubArray1(input) {

    let sum = 0,
    map = {0:[-1]};

    for (let i = 0; i < input.length; i++) {
        sum += input[i];

        if (!map[sum]) {
            map[sum] = [i];
        }else {
            map[sum].push(i)

            let val = map[sum];
            for (let j = 0; j < val.length; j++) {
                console.log(val[j])
            }
        }
    }

}

上面的 function 不工作不給所有子數組? 有什么辦法嗎?

我從這里參考https://www.techiedelight.com/find-sub-array-with-0-sum/

該站點有一篇題為“在數組中查找具有給定總和的子數組”的文章。 它具有 C++、Java 和 Python 實現。

我剛剛將 Java(和一點 Python)代碼移植到 JavaScript。

 const main = () => { const input = [4, 2, -3, -1, 0, 4], target = 0; console.log(subarraySum(input, target)); console.log(subarraySumMap(input, target)); }; const subarraySum = (nums, k) => { const results = []; for (let start = 0; start < nums.length; start++) { let sum = 0; for (let end = start; end <= nums.length; end++) { sum += nums[end]; if (sum === k) { results.push(nums.slice(start, end + 1)); } } } return results; } const subarraySumMap = (nums, k) => { const insert = (hashMap, key, value) => hashMap.set(key, (hashMap.get(key) || []).concat(value)); const results = [], hashMap = new Map(); let sum = 0; insert(hashMap, 0, -1); for (let index = 0; index < nums.length; index++) { sum += nums[index]; if (hashMap.has(sum - k)) { let list = hashMap.get(sum - k); list.forEach(value => { results.push(nums.slice(value + 1, index + 1)); }); } insert(hashMap, sum, index); } return results; } main();
 .as-console-wrapper { top: 0; max-height: 100%;important; }
 <:-- References: --> <.-- https://leetcode.com/problems/subarray-sum-equals-k/solution/ --> <.-- https,//www,techiedelight,com/find-subarrays-given-sum-array/ --> <,-- ∀ x ⊆ ∑ { 4, 2, -3, -1, 0, 4 } = 0 -->

暫無
暫無

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

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