问题:
难度:easy
说明:
给一个数组里面只有01两种元素,然后要求0 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.
我的代码:
将数组所有数加起来,用hashmap存放每一次sum,然后将index放入即可,最后返回暂存的result
class Solution {
int[] maps = new int[]{-1,1};
public int findMaxLength(int[] nums) {
if(nums == null ||nums.length < 2) return 0;
int len = nums.length;
int[] bigmap = new int[(len << 1) + 1];
bigmap[len] = -1;
int sum = 0;
int index = 0;
int result = 0;
for(int i = 0;i < len; i ++) {
sum += maps[nums[i]];
index = sum + len;
// 如果改结果是0,就放入index,如果不为0则比较遍历i和index长度大小
if(bigmap[index] != 0) {
result = Math.max(result, (i + 1 - (index == len ? 0 : bigmap[index])));
} else {
bigmap[index] = i + 1;
}
}
return result;
}
}