classSolution { public: intnumSubarraysWithSum(vector<int>& nums, int goal){ int sum = 0; unordered_map<int, int> cnt; int ret = 0; for (auto& num : nums) { cnt[sum]++; sum += num; ret += cnt[sum - goal]; } return ret; } };
[sol1-Java]
1 2 3 4 5 6 7 8 9 10 11 12 13
classSolution { publicintnumSubarraysWithSum(int[] nums, int goal) { intsum=0; Map<Integer, Integer> cnt = newHashMap<Integer, Integer>(); intret=0; for (int num : nums) { cnt.put(sum, cnt.getOrDefault(sum, 0) + 1); sum += num; ret += cnt.getOrDefault(sum - goal, 0); } return ret; } }
[sol1-C#]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
publicclassSolution { publicintNumSubarraysWithSum(int[] nums, int goal) { int sum = 0; Dictionary<int, int> cnt = new Dictionary<int, int>(); int ret = 0; foreach (int num in nums) { if (cnt.ContainsKey(sum)) { cnt[sum]++; } else { cnt.Add(sum, 1); } sum += num; int val = 0; cnt.TryGetValue(sum - goal, out val); ret += val; } return ret; } }
[sol1-Golang]
1 2 3 4 5 6 7 8 9 10
funcnumSubarraysWithSum(nums []int, goal int) (ans int) { cnt := map[int]int{} sum := 0 for _, num := range nums { cnt[sum]++ sum += num ans += cnt[sum-goal] } return }
[sol1-JavaScript]
1 2 3 4 5 6 7 8 9 10 11
var numSubarraysWithSum = function(nums, goal) { let sum = 0; const cnt = newMap(); let ret = 0; for (const num of nums) { cnt.set(sum, (cnt.get(sum) || 0) + 1); sum += num; ret += cnt.get(sum - goal) || 0; } return ret; };