https://leetcode-cn.com/problems/contiguous-array/
给定一个二进制数组, 找到含有相同数量的 0 和 1 的最长连续子数组(的长度)。
示例 1:
输入: [0,1] 输出: 2 说明: [0, 1] 是具有相同数量0和1的最长连续子数组。示例 2:
输入: [0,1,0] 输出: 2 说明: [0, 1] (或 [1, 0]) 是具有相同数量0和1的最长连续子数组。
注意: 给定的二进制数组的长度不会超过50000。
public int findMaxLength(int[] nums) {
int ans = 0,sum = 0;
for(int i=0;i<nums.length;i++)if(nums[i]==0)nums[i]=-1;
HashMap<Integer,Integer> map = new HashMap();
for(int i=0;i<nums.length;i++) {
sum+=nums[i];
if(sum == 0) { if(i >= ans) ans = i+1; }
if(map.get(sum) == null) { map.put(sum,i); continue; }
int temp = i - map.get(sum);
if(temp > ans) ans=temp;
}
return ans;
}