[leetcode-560-Subarray Sum Equals K]

Given an array of integers and an integer k, you need to find the total number of continuous subarrays whose sum equals to k.
Example 1:
Input:nums = [1,1,1], k = 2
Output: 2
Note:
The length of the array is in range [1, 20,000].
The range of numbers in the array is [-1000, 1000] and the range of the integer k is [-1e7, 1e7].

思路:

感觉这个跟已知数组,求数组区间和那个很类似,[leetcode-303-Range Sum Query - Immutable]

这个是:已知区间和为k,求一共有多少个区间的和为k。

可以通过累积和数组sums来统计数组nums当前元素nums[i]之前所有元素的和,

比如:k= 3

nums: [1, -1, 5, -2, 3], 则得到

sums: [1, 0, 5, 3, 6]

我们可以看到累积和sums的第四个数字为3,则说明前四个数字就是符合题意的一个子数组,再来看第二个例子:

nums: [-2, -1, 2, 1], k = 1

sums: [-2, -3, -1, 0]

可以在nums里找到 -1,2 的和为1,又nums[0]+nums[1]+nums[2] = sums[0]+ nums[1]+nums[2] =  sums[2] 。

则sums[0]+k = sums[2] ,区间和k = sums[2] - sums[0] = (-1) - (-2),

sums[2] - k =sums[0],说明存在区间nums[1],nums[2]的和为k。

然后,再用一个哈希表来建立累积和 与 其坐标之间的映射。如果 H[ sum[i] - k ]>0 则说明存在区间和为k。

int subarraySum(vector<int>& nums, int k)
  {
      int n = nums.size();
      vector<int >sum(n+1);//记录累加和
      for(int i =1;i<=n;i++)
      {
          sum[i] = sum[i-1]+nums[i-1];
      }
      map<int ,int > H;
      H[0] = 1;
      int ret = 0;
      for(int i =1;i<=n;i++)
      {
           ret += H[ sum[i] - k ];
           H[sum[i]]++;
      }
      return ret;
}

参考:

http://www.cnblogs.com/grandyang/p/5336668.html

转载于:https://www.cnblogs.com/hellowooorld/p/6789307.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值