forked from lazzzis/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.java
28 lines (28 loc) · 885 Bytes
/
Solution.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class Solution {
public boolean checkSubarraySum(int[] nums, int k) {
if (k < 0) k = -k;
if (nums.length <= 1) return false;
if (k == 1 && nums.length >= 2) return true;
Map<Integer, Integer> map = new HashMap<>();
map.put(0, -1);
int sum = 0;
for (int i = 0; i < nums.length; i++) {
sum += nums[i];
if (k == 0) {
if (map.containsKey(sum) && i - map.get(sum) >= 2) {
return true;
}
} else {
int n = sum;
while (n >= 0) {
if (map.containsKey(n) && i - map.get(n) >= 2) {
return true;
}
n -= k;
}
}
if (!map.containsKey(sum)) map.put(sum, i);
}
return false;
}
}