-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path26-ContigousArray.java
53 lines (48 loc) · 1.41 KB
/
26-ContigousArray.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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
class Solution {
public int findMaxLength(int[] nums) {
int len = nums.length;
int answer = 0;
for (int i = 0; i < len; i++) {
if (nums[i] == 0) nums[i] = -1;
}
int[] pref = new int[len + 1];
pref[0] = 0;
for (int i = 0; i < len; i++) {
pref[i + 1] = pref[i] + nums[i];
}
HashMap<Integer, Integer> first_oc = new HashMap<>();
for (int i = 0; i < len + 1; i++) {
int x = pref[i];
if (first_oc.containsKey(x)) {
answer = Math.max(answer, i - first_oc.get(x));
} else {
first_oc.put(x, i);
}
}
return answer;
}
}
class Solution {
public int findMaxLength(int[] nums) {
int len = nums.length;
int answer = 0;
for (int i = 0; i < len; i++) {
if (nums[i] == 0) nums[i] = -1;
}
int[] pref = new int[len + 1];
pref[0] = 0;
for (int i = 0; i < len; i++) {
pref[i + 1] = pref[i] + nums[i];
}
HashMap<Integer, Integer> first_oc = new HashMap<>();
for (int i = 0; i < len + 1; i++) {
int x = pref[i];
if (first_oc.containsKey(x)) {
answer = Math.max(answer, i - first_oc.get(x));
} else {
first_oc.put(x, i);
}
}
return answer;
}
}