Skip to content

Commit db1d98c

Browse files
authored
Merge pull request #137 from qilingit/day26
Add Java solution for day 26: Contiguous Array
2 parents 89c6ae7 + 94aa849 commit db1d98c

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
/**
2+
* Use a hashMap to stock the index and the count, the count minus 1 if reach 0, plus 1 if reach 1.
3+
* We compare current length of contiguous array with the maxLength
4+
*/
5+
/**
6+
* Time complexity: O(n), because a signle loop of nums[]
7+
* Space complexity: O(n), becasue we build a HashMap
8+
*/
9+
class Solution {
10+
public int findMaxLength(final int[] nums) {
11+
int maxLength = 0;
12+
int count = 0;
13+
final Map<Integer, Integer> countsMap = new HashMap<>();
14+
15+
for (int i = 0; i < nums.length; i++) {
16+
if (nums[i] == 0) {
17+
count -= 1;
18+
} else {
19+
count += 1;
20+
}
21+
22+
/**
23+
* if the count is 0, it means that from the start of index, we have nothing added to the count,
24+
* So the length of contiguous array is from the starter to current index
25+
*/
26+
if (count == 0) {
27+
maxLength = Math.max(maxLength, (i + 1));
28+
} else if (countsMap.containsKey(count)) {
29+
/**
30+
* If the count is contained in the map, it means that for the index of contained count to
31+
* the current index, we have nothing added, we can build a contignous array, it's length is
32+
* i minus index of contained count
33+
*/
34+
maxLength = Math.max(maxLength, i - countsMap.get(count));
35+
} else {
36+
countsMap.put(count, i);
37+
}
38+
39+
}
40+
return maxLength;
41+
}
42+
}

0 commit comments

Comments
 (0)