Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // LeetCode URL: https://leetcode.com/problems/subarray-sum-equals-k/
- import java.util.HashMap;
- /**
- * Maintain a count of cumulative sum in a map.
- *
- * Refer: https://leetcode.com/problems/subarray-sum-equals-k/discuss/190674
- *
- * Time Complexity: O(N)
- *
- * Space Complexity: O(N)
- *
- * N = Length of the input nums array.
- */
- class Solution {
- public int subarraySum(int[] nums, int k) {
- if (nums == null || nums.length == 0) {
- return 0;
- }
- int count = 0;
- int sum = 0;
- HashMap<Integer, Integer> map = new HashMap<>();
- map.put(0, 1);
- for (int num : nums) {
- sum += num;
- if (map.containsKey(sum - k)) {
- count += map.get(sum - k);
- }
- map.put(sum, map.getOrDefault(sum, 0) + 1);
- }
- return count;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement