leetcode

Solution to some Leetcode problems written in C++
git clone git://git.dimitrijedobrota.com/leetcode.git
Log | Files | Refs | README | LICENSE

0560.cpp (484B)


      1 class Solution {
      2   public:
      3     int subarraySum(vector<int> &nums, int k) {
      4         int n = nums.size(), res = 0, sum = 0;
      5         unordered_map<int, int> um;
      6         vector<int> prefix(n);
      7         for (int i = 0; i < n; i++)
      8             sum = prefix[i] = sum + nums[i];
      9 
     10         for (int i = 0; i < n; i++) {
     11             if (prefix[i] == k) res++;
     12             if (um.count(prefix[i] - k)) res += um[prefix[i] - k];
     13             um[prefix[i]]++;
     14         }
     15 
     16         return res;
     17     }
     18 };