[英]get all subarray which have sum 0 in javascript?
I am trying to get all subarray which have sum 0 in javascript?我正在尝试获取 javascript 中总和为 0 的所有子数组? I am able to do that in O(n^2)
like this我可以像这样在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
}
when I call above function console.log(getSubArray([1, 2, -3, 0, 4, -5, 2, -1]))
it is printed in all subarray but in O(n^2)
.当我在 function console.log(getSubArray([1, 2, -3, 0, 4, -5, 2, -1]))
上面调用时,它会打印在所有子数组中,但在O(n^2)
中。
I tried to optimism this in O(n)
using map我尝试使用 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])
}
}
}
}
above function not working not giving all subarray?上面的 function 不工作不给所有子数组? is there any way to do this?有什么办法吗?
I take the reference from here https://www.techiedelight.com/find-sub-array-with-0-sum/我从这里参考https://www.techiedelight.com/find-sub-array-with-0-sum/
That site has an article titled "Find subarrays with given sum in an array" .该站点有一篇题为“在数组中查找具有给定总和的子数组”的文章。 It has C++, Java, and Python implementations.它具有 C++、Java 和 Python 实现。
I just ported the Java (and a bit of Python) code to JavaScript.我刚刚将 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.