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.
这道题我想用DP做的,结果Memory Limit Exceeded了,真是屮艸芔茻...注意一个测试用例:[0,0,0,1,1,1,0],返回结果 6 。
这道题有点类似于之前的一道题 http://blog.csdn.net/huanghanqian/article/details/77054149,从树的根一直遍历到叶,找到所有的 和为target的路径(不一定非得以根结点开始以叶节点结尾)。只要把这道题的0想象成-1,就会转化为:找到最长的串使得 和为0。然后解决方法就跟之前的那道题类似啦。
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.
public int findMaxLength(int[] nums) {
int n=nums.length;
if(n<2){
return 0;
}
int maxLength=0;
//map存储 <[0,index]范围内的和,index> ,且 是 得到该和的最小的index
HashMap<Integer, Integer> map=new HashMap<Integer, Integer>();
int sum=0;//sum是0~i范围的和
map.put(0, -1);
for(int i=0;i<n;i++){
if(nums[i]==1){
sum+=1;
}
else{
sum+=-1;
}
//sum-sum=0
if(map.get(sum)!=null){
int length=i-map.get(sum);
if(length>maxLength){
maxLength=length;
}
}
else {
map.put(sum,i);
}
}
return maxLength;
}
大神们也都用的这个解法。
这道题有solutions: https://leetcode.com/problems/contiguous-array/solution/#approach-3-using-hashmap-acceptedApproach #3 Using HashMap [Accepted]
Algorithm
我们使用一个 HashMap map 来存储 (index,count),当我们遇到一个之前未曾出现的count时,将该条目push进map。之后再碰到该count时,使用它对应的 index 来找 最大的使得count为0的子串。
Java
public class Solution { public int findMaxLength(int[] nums) { Map<Integer, Integer> map = new HashMap<>(); map.put(0, -1); int maxlen = 0, count = 0; for (int i = 0; i < nums.length; i++) { count = count + (nums[i] == 1 ? 1 : -1); if (map.containsKey(count)) { maxlen = Math.max(maxlen, i - map.get(count)); } else { map.put(count, i); } } return maxlen; } }
Complexity Analysis
-
Time complexity : O(n). The entire array is traversed only once.
-
Space complexity : O(n). Maximum size of the HashMap map will be n, if all the elements are either 1 or 0.