LeetCode 560. Subarray Sum Equals K

Problem

Given an array of integers and an integer k, you need to find the total number of continuous subarrays whose sum equals to k.

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/subarray-sum-equals-k

Method One:枚举

本来以为必定超时然后WA,竟然AC了hhhhh

Java

class Solution {
    public int subarraySum(int[] nums, int k) {
        int ans = 0;
        int size = nums.length;
        for (int i = 0; i < size; i++) {
            int sum = 0;
            for (int j = i; j < size; j++) {
                sum += nums[j];
                if (sum==k) ans++;
            }
        }
        return ans;
    }
}

Method Two:前缀和

这种方法我在做的时候只有一点点思路,具体怎么做并没有想到。
思路是这样的:遍历元素至ipre为目前所有数字的和。如果子数组[t...i]的和为n,且n==k(k为目标数字),则当pre-n==m的情况存在,即存在t个子数组[0...t]的和为m时,解的数量加t

C++

class Solution {
public:
    int subarraySum(vector<int>& nums, int k) {
    	// 计数菌
		int ans = 0;
		// 前缀和
        int pre = 0;
        // 表示:子数组的和为key的情况有val种
        map<int, int>mp;
        mp[0] = 1;
        for (auto x : nums) {
        	// 更新前缀和
            pre += x;
            // 即思路中提到的情况。存在mp[key]个子数组和为pre-k
            if (mp.find(pre-k)!=mp.end()) ans += mp[pre-k];
            // 更新存储
            mp[pre]++;
        }
        return ans;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值