[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:

  1. The length of the array is in range [1, 20,000].
  2. The range of numbers in the array is [-1000, 1000] and the range of the integer k is [-1e7, 1e7].

思路

首先还是建立一个map,从数组的累积和映射到索引上,这样我们就可以在O(1)的时间内求出任意子区间的和。然后试图以每个元素i为子区间的末尾,计算[0, j] (j < i)的区间和需要是多少,才能使得[j + 1, i]区间的和为k,然后就在map中查找。每找到一个,结果就加1,最后返回结果就可以了。由于不同的索引可能会对应同一个累积和,所以我们需要用multimap来实现。算法的时间复杂度是O(nlogn),空间复杂度是O(n)。

代码

class Solution {
public:
    int subarraySum(vector<int>& nums, int k) {
        vector<int> sums(nums.size() + 1, 0);
        multimap<int, int> mp;   // {sum, index}
        mp.insert(make_pair(0, 0));
        for (int i = 1; i <= nums.size(); ++i) {
            sums[i] = sums[i - 1] + nums[i - 1];
            mp.insert(make_pair(sums[i], i));
        }
        int ans = 0;
        for (int i = 1; i < sums.size(); ++i) {
            int value = sums[i] - k;
            auto ret = mp.equal_range(value);
            for (auto it = ret.first; it != ret.second; ++it) {
                if (it->second < i) {
                    ++ans;
                }
            }
        }
        return ans;
    }
};

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值