Advertisement
hoewarden

Untitled

Aug 26th, 2019
410
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.85 KB | None | 0 0
  1. #include <unordered_map>
  2.  
  3. class Solution {
  4. public:
  5. int subarraySum(vector<int>& nums, int k) {
  6. int res = 0;
  7. // partial sum -> how many times we had this time so far
  8. unordered_map<int, int> m;
  9. int sum = 0;
  10. for(auto i = nums.cbegin(); i != nums.cend(); i++) {
  11. sum += *i;
  12. if(sum == k) {
  13. res++;
  14. }
  15. // partial sums before now, mathching with sum into k
  16. auto match = m.find(sum - k);
  17. if(match != m.end()) {
  18. res += match->second;
  19. }
  20. // then insert current partial sum into the map
  21. auto cur = m.find(sum);
  22. if(cur != m.end()) {
  23. cur->second++;
  24. } else {
  25. m[sum] = 1;
  26. }
  27. }
  28. return res;
  29. }
  30. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement