MrainW's Home

All things come to those who wait!

0%

LeetCode 560. Subarray Sum Equals K

Question

Given an array of integers nums and an integer k, return the total number of continuous subarrays whose sum equals to k.

https://leetcode.com/problems/subarray-sum-equals-k/

  • Solution1
1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
public int subarraySum(int[] nums, int k) {
Map<Integer, Integer> map = new HashMap<>();
int sum = 0, res = 0;
map.put(0, 1);
for (int num : nums){
sum += num;
if (map.containsKey(sum - k)) res += map.get(sum - k);
map.put(sum, map.getOrDefault(sum, 0) + 1);
}
return res;
}
}

Complexity:

Time complexity: O(n)

Space complexity: O(n)

Welcome to my other publishing channels