C++ sum and count


  • 0
    B
    class Solution {
    public:
        int subarraySum(vector<int>& nums, int k) {
            unordered_map<int,int>count;
            int sum = 0;
            for(auto & e : nums)
            {
                sum += e;
                count[sum]++;
            }
            sum = 0;
            int ans = 0;
            for(auto e : nums)
            {
                sum += e;
                if(sum == k) ans += 1;
                count[sum]--;
                ans += count[sum+k];
            }
            
            return ans;
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.