O(n) C++ concise solution


  • 0
    I
    class Solution {
    public:
        int subarraySum(vector<int>& nums, int k) {
            unordered_map<int,int> m;
            int sum = 0, res = 0;
            ++m[0];
            for(int i = 0; i < nums.size(); ++i)
            {
                sum += nums[i];
                if(m.find(sum-k) != m.end())
                   res += m[sum-k];
                ++m[sum];
            }
            return res;
        }
    };
    

  • 0
    R

    Hey,

    I was having trouble passing test cases with unordered_map, did you have any issues with this?

    Thanks!


Log in to reply
 

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