0%

Leetcode525-contiguousArray

Description

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

Example

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.

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
//The idea is to change 0 in the original array to -1. Thus, if we find SUM[i, j] == 0 then we know there are even number of -1 and 1 between index i and j. Also put the sum to index mapping to a HashMap to make search faster

class Solution {
public int findMaxLength(int[] nums) {
if (nums == null || nums.length == 0) return 0;

HashMap<Integer, Integer> map = new HashMap<>();
int sum = 0;
map.put(0, -1);

int res = 0;
for (int i = 0; i < nums.length; i++){
sum += nums[i] == 0 ? -1 : 1;
if (map.containsKey(sum)){
res = Math.max(res, i - map.get(sum));
}
else map.put(sum, i);
}

return res;
}
}