525. Contiguous Array

Given a binary array, find the maximum length of a contiguous subarray with equal number of 0 and 1.

Example 1:

1
2
3
Input: [0,1]
Output: 2
Explanation: [0, 1] is the longest contiguous subarray with equal number of 0 and 1.

Example 2:

1
2
3
Input: [0,1,0]
Output: 2
Explanation: [0, 1] (or [1, 0]) is a longest contiguous subarray with equal number of 0 and 1.

Note: The length of the given binary array will not exceed 50,000.

解法1:

很好的一题,用到了2sum = zero的特殊解法(用hashmap), 也用到了变换条件使得题目变得更有利。
把0变成-1的话这题的条件就变成找一个continuous array使得加和为1并且最长。
加和为0很好办,看sum是否出现过,如果出现过,更新最长距离。要注意初始条件,第一个点是设成map.put(0, -1)
C++

1

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
public class Solution {
public int findMaxLength(int[] nums) {
if (nums == null || nums.length == 0) {
return 0;
}
for (int i = 0; i < nums.length; i++) {
if (nums[i] == 0) {
nums[i] = -1;
}
}
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
map.put(0, -1);
int sum = 0, max = 0;
for (int i = 0; i < nums.length; i++) {
sum += nums[i];
if (map.containsKey(sum)) {
// prefix sum exists, meaning sum[i, j] = 0 => equal number of 1 and 0 (now -1)
max = Math.max(max, i - map.get(sum));
} else {
map.put(sum, i);
}
}
return max;
}
}