Given a binary array, find the maximum length of a contiguous subarray with equal number of 0 and 1.
Example 1:
Input: [0,1]
Output: 2
Explanation: [0, 1] is the longest contiguous subarray with equal number of 0 and 1.
Example 2:
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.
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/contiguous-array
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
1. 把nums中的0都变成-1,那么,如果一段序列的和是0,那么它的0和1 数目是相等的复合题意的。
2. 用一个map存储,key值是和,value是index,即表示到index位置,和是多少。
3. 从头开始遍历,并且对每个遍历到的数字进行累加,如果我们计算到的和,是之前有遇到过的,那么这一段序列的和就是0,满足题意。
class Solution {
public int findMaxLength(int[] nums) {
if (nums.length == 0 )
return 0;
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
map.put(0, - 1);
int ans = 0;
int sum = 0;
for (int i = 0; i < nums.length; i++) {
if (nums[i] == 0) {
sum += -1;
} else {
sum += 1;
}
if (map.containsKey(sum)) {
ans = Math.max(ans, i - map.get(sum));
} else {
map.put(sum, i);
}
}
return ans;
}
}