【題解】LeetCode 560. Subarray Sum Equals K

【題目敘述】https://leetcode.com/problems/subarray-sum-equals-k/

class Solution {
public:
    int subarraySum(vector<int>& nums, int k) {
        int sz = nums.size(), ans = 0;
        int p[sz+5];
        p[0] = 0;
        for (int i = 1; i <= sz; i++){
            p[i] = p[i-1] + nums[i-1];
        }
        map <int, int> mp;
        mp[0] = 1;
        for (int i = 1; i <= sz; i++){
            if (mp.count(p[i]-k)) ans += mp[p[i]-k];
            mp[p[i]] += 1;
        }
        return ans;
    }
};
分享本文 Share with friends