Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit a17a0c9

Browse files
refactor 523
1 parent 02c14f6 commit a17a0c9

File tree

2 files changed

+15
-3
lines changed

2 files changed

+15
-3
lines changed

src/main/java/com/fishercoder/solutions/_523.java

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,17 +8,17 @@ public class _523 {
88
public static class Solution1 {
99
/**
1010
* reference: https://discuss.leetcode.com/topic/80793/java-o-n-time-o-k-space/20
11-
* "The reason we use modulus is:
11+
* "The reason we use modulo is:
1212
* (a+(n*x))%x is same as (a%x)
13-
* e.g. in case of the array [23,2,6,4,7] the running sum is [23,25,31,35,42]
13+
* e.g. in case of the array [23,2,6,4,7] and k = 6 the running sum is [23,25,31,35,42]
1414
* and the remainders are [5,1,1,5,0].
1515
* We got reminder 5 at index 0 and at index 3.
1616
* That means, in between these two indexes we must have added a number which is multiple of the k.
1717
* Hope this clarifies your doubt :)"
1818
*/
1919
public boolean checkSubarraySum(int[] nums, int k) {
2020
Map<Integer, Integer> map = new HashMap<>();
21-
map.put(0, -1);
21+
map.put(0, -1);//this line is critical to mark the beginning of the prefix sum, so that next time, when we encounter a running sum of zero, we know that's the answer, see test case 11
2222
int sum = 0;
2323
for (int i = 0; i < nums.length; i++) {
2424
sum += nums[i];
@@ -41,6 +41,9 @@ public boolean checkSubarraySum(int[] nums, int k) {
4141
}
4242

4343
public static class Solution2 {
44+
/**
45+
* O(n^2), this will time out on LeetCode.
46+
*/
4447
public boolean checkSubarraySum(int[] nums, int k) {
4548
if (nums == null || nums.length == 0) {
4649
return false;

src/test/java/com/fishercoder/_523Test.java

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -109,4 +109,13 @@ public void test10() {
109109
assertEquals(expected, solution2.checkSubarraySum(nums, k));
110110
}
111111

112+
@Test
113+
public void test11() {
114+
nums = new int[]{23, 2, 4, 6, 6};
115+
expected = true;
116+
k = 7;
117+
assertEquals(expected, solution1.checkSubarraySum(nums, k));
118+
assertEquals(expected, solution2.checkSubarraySum(nums, k));
119+
}
120+
112121
}

0 commit comments

Comments
 (0)