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.
题目的意思是找一个最长子数组,子数组里0和1的数量相等,返回这个子数组的长度即可。
注意:此数组为binary array,所以数组里面只有0和1,开始读题时忽略了此条件,导致把题目复杂化了!
思路:将数组中所有的0用-1代替,这样是为了使用HashMap的key唯一性,出现相同的Key便可用于计算符合条件的子数组的长度了。用HashMap来记录前N项元素的和,当HashMap中出现相同的和时,说明有相同数量的0和1,用max记录子数组的长度,比较max的值,返回最大的max,即为要找的最大子数组的长度。
public class Solution {
public int findMaxLength(int[] nums) {
//把所有的0变成-1,这样检测到map里有相同的key时,说明已经有了相同数量的0和1
for(int i=0;i<nums.length;i++){
if(nums[i]==0) nums[i]=-1;
}
//key是sum,value是sum所对应的索引
HashMap<Integer,Integer> IndexofSum=new HashMap<Integer,Integer>();
//map.put是在HashMap中放入key-value pair
IndexofSum.put(0, -1);
int sum=0;
int max=0;
for(int i=0;i<nums.length;i++){
sum+=nums[i];
//如果HashMap中包含某个sum,则说明此时出现了相同数量的0和1,用max来记录子数组的长度
if(IndexofSum.containsKey(sum)){
max=Math.max(max, i-IndexofSum.get(sum));
}
else{IndexofSum.put(sum,i);}
}
return max;
}
}