Advertisement
1988coder

560. Subarray Sum Equals K

Jan 6th, 2019
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.87 KB | None | 0 0
  1.  
  2. // LeetCode URL: https://leetcode.com/problems/subarray-sum-equals-k/
  3. import java.util.HashMap;
  4.  
  5. /**
  6.  * Maintain a count of cumulative sum in a map.
  7.  *
  8.  * Refer: https://leetcode.com/problems/subarray-sum-equals-k/discuss/190674
  9.  *
  10.  * Time Complexity: O(N)
  11.  *
  12.  * Space Complexity: O(N)
  13.  *
  14.  * N = Length of the input nums array.
  15.  */
  16. class Solution {
  17.     public int subarraySum(int[] nums, int k) {
  18.         if (nums == null || nums.length == 0) {
  19.             return 0;
  20.         }
  21.  
  22.         int count = 0;
  23.         int sum = 0;
  24.         HashMap<Integer, Integer> map = new HashMap<>();
  25.         map.put(0, 1);
  26.  
  27.         for (int num : nums) {
  28.             sum += num;
  29.             if (map.containsKey(sum - k)) {
  30.                 count += map.get(sum - k);
  31.             }
  32.             map.put(sum, map.getOrDefault(sum, 0) + 1);
  33.         }
  34.  
  35.         return count;
  36.     }
  37. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement