[leetcode] 560. Subarray Sum Equals K

Description

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].

分析

题目的意思是:找出一个数组里面连续子数组的和为K的子数组的个数。

  • 用一个map存起来,mp[0]的初始值为1,用于然后mp记录的是前m项的求和,mp[sum-k]如果为1,表明存在一个连续子序列的值为k,这需要找个test case模拟一下就行了。

C++

class Solution {
public:
    int subarraySum(vector<int>& nums, int k) {
        int sum=0;
        map<int,int> mp;
        int count=0;
        mp[0]++;
        for(int i=0;i<nums.size();i++){
            sum+=nums[i];
            count+=mp[sum-k];
            mp[sum]++;  
        }
        return count;
    }
};

Python

这道题重在理解,实现比较简单,然而居然翻车了,看来还需要多做几遍代码题,直到记住。
在这里插入图片描述

class Solution:
    def subarraySum(self, nums: List[int], k: int) -> int:
        m_sum = defaultdict(int)
        # 初始前缀和为0的出现次数为1
        m_sum[0]=1
        sum_num=0
        res = 0
        for i in range(len(nums)):
            sum_num+=nums[i]
            res+=m_sum[sum_num-k]
            m_sum[sum_num]+=1
        return res

参考文献

LeetCode Subarray Sum Equals K 子数组和为K
560. Subarray Sum Equals K

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

农民小飞侠

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值