|
17 | 17 | */ |
18 | 18 | public class _560 { |
19 | 19 |
|
20 | | - /**credit: https://discuss.leetcode.com/topic/87850/java-solution-presum-hashmap |
21 | | - * We know the key to solve this problem is SUM[i, j]. |
22 | | - * So if we know SUM[0, i - 1] and SUM[0, j], |
23 | | - * then we can easily get SUM[i, j] via (SUM[0, j] - SUM[0, i-1]). |
24 | | - * To achieve this, we just need to go through the array, |
25 | | - * calculate the current sum and save number of all seen PreSum to a HashMap. |
26 | | - * |
27 | | - * Time complexity O(n), Space complexity O(n).*/ |
28 | | - public int subarraySum(int[] nums, int k) { |
29 | | - Map<Integer, Integer> preSum = new HashMap(); |
30 | | - int sum = 0; |
31 | | - int result = 0; |
32 | | - preSum.put(0, 1); |
33 | | - for (int i = 0; i < nums.length; i++) { |
34 | | - sum += nums[i]; |
35 | | - if (preSum.containsKey(sum - k)) { |
36 | | - result += preSum.get(sum - k); |
| 20 | + public static class Solution1 { |
| 21 | + |
| 22 | + /** |
| 23 | + * credit: https://discuss.leetcode.com/topic/87850/java-solution-presum-hashmap |
| 24 | + * We know the key to solve this problem is SUM[i, j]. |
| 25 | + * So if we know SUM[0, i - 1] and SUM[0, j], |
| 26 | + * then we can easily get SUM[i, j] via (SUM[0, j] - SUM[0, i-1]). |
| 27 | + * To achieve this, we just need to go through the array, |
| 28 | + * calculate the current sum and save number of all seen PreSum to a HashMap. |
| 29 | + * <p> |
| 30 | + * Time complexity O(n), Space complexity O(n). |
| 31 | + */ |
| 32 | + public int subarraySum(int[] nums, int k) { |
| 33 | + Map<Integer, Integer> preSum = new HashMap(); |
| 34 | + int sum = 0; |
| 35 | + int result = 0; |
| 36 | + preSum.put(0, 1); |
| 37 | + for (int i = 0; i < nums.length; i++) { |
| 38 | + sum += nums[i]; |
| 39 | + if (preSum.containsKey(sum - k)) { |
| 40 | + result += preSum.get(sum - k); |
| 41 | + } |
| 42 | + preSum.put(sum, preSum.getOrDefault(sum, 0) + 1); |
37 | 43 | } |
38 | | - preSum.put(sum, preSum.getOrDefault(sum, 0) + 1); |
| 44 | + return result; |
39 | 45 | } |
40 | | - return result; |
41 | 46 | } |
42 | 47 |
|
43 | 48 | } |
0 commit comments