我想在数组中找到具有给定总和的子数组#。但是代码不符合我的要求

时间:2019-01-25 16:35:43

标签: javascript

function getSubArrayCount(arr, sum) {

    var count = 0 , n = arr.length, prevSum = new Map(), res = 0,currsum = 0;  

    for (var i = 0; i < n; i++) {  
        currsum += arr[i];  

        if (currsum == sum)   
            res++;          

        if (prevSum.has(currsum - sum)){

            res += prevSum.get(currsum - sum);  
        }
        count = prevSum.get(currsum);
        if (count === null){

            prevSum.set(currsum, 1); 
        }
        else{

            prevSum.set(currsum, count+1);  
        }}  
  console.log(res);
  return res;
}
getSubArrayCount([1,2,3,2,1,8,-3],5);
getSubArrayCount([1,2,3,4],10);

这些条件应该得到满足

1)。返回类型应为字符串

2).getSubArrayCount([1,2,3,2,1,8,-3],5)应该等于3

3).getSubArrayCount([1,2,3,4],10)应该等于1

4)。答案应在任何给定的条件下有效

1 个答案:

答案 0 :(得分:0)

function getSubArrayCount(array, target) {
  var sumCount = 0 , currentSum = 0;
  array.forEach((number, index) => {
  currentSum = array[index];
  for (let i = (index + 1); i < (array.length); i++) {
            currentSum += array[i];
        if (currentSum === target) {
            sumCount++;
        }
    }
  });
  console.log(sumCount);
  return sumCount.toString();
}

alert(getSubArrayCount([2,98,0,100,102,-2,50,50], 100)); // "5"
alert(getSubArrayCount([1,2,3,2,1,8,-3],5)) // "3"
alert(getSubArrayCount([1,2,3,4],10)) // "1"