问题:java
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:spa
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.code
解决:https://discuss.leetcode.com/topic/79906/easy-java-o-n-solution-presum-hashmapleetcode
① 找到最长的包含0,1(或1,0)的子串,让咱们找相邻的子数组使其0和1的个数相等。对于求子数组的问题,咱们须要时刻记着求累积和是一种很犀利的工具,可是这里怎么将子数组的和跟0和1的个数之间产生联系呢?咱们须要用到一个trick,遇到1就加1,遇到0,就减1,这样若是某个子数组和为0,就说明0和1的个数相等。知道了这一点,咱们用一个哈希表创建子数组之和跟结尾位置的坐标之间的映射。若是某个子数组之和在哈希表里存在了,说明当前子数组减去哈希表中存的那个子数字,获得的结果是中间一段子数组之和,必然为0,说明0和1的个数相等,咱们更新结果res。。。get
class Solution { //102ms
public int findMaxLength(int[] nums) {
for (int i = 0;i < nums.length;i ++){
if (nums[i] == 0) nums[i] = -1;
}
Map<Integer,Integer> map = new HashMap<>();
map.put(0,-1);
int sum = 0;
int max = 0;
for (int i = 0;i < nums.length;i ++){
sum += nums[i];
if (map.containsKey(sum)){
max = Math.max(max,i - map.get(sum));
}else {
map.put(sum,i);
}
}
return max;
}
}hash
② 在discuss中看到的。it
class Solution { //45ms
public int findMaxLength(int[] nums) {
if (nums == null || nums.length == 0) return 0;
int[] map = new int[(2*nums.length) + 1];
Arrays.fill(map, -2);
map[nums.length] = -1;
int max = 0;
int sum = 0;
for (int i = 0;i < nums.length;i ++) {
sum = sum + (nums[i] == 0 ? -1 : 1);
if (map[sum + nums.length] >= -1) {
max = Math.max(max, i - map[sum + nums.length]);
} else {
map[sum + nums.length] = i;
}
}
return max;
}
}io