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.
连续数组。给定一个二进制数组, 找到含有相同数量的 0 和 1 的最长连续子数组的长度。
这个题目看似简单但是这个思路比较难想到。这个题的tag是hash table,感觉可以往前缀和为0的思路上去靠。题目问的是包含相同数量的0和1的子数组的长度,如果把0替换成-1,也就是说满足条件的子数组的和会是0。所以做法是创建一个hashmap记录前缀和和他最后一次出现的位置的index。扫描的时候就按照加前缀和的方式做,当遇到某一个前缀和X已经存在于hashmap的时候,就知道这一段区间内的子数组的和为0了,否则这个前缀和不可能重复出现。举个例子,比如[0,1,0]好了,一开始往hashmap存入了初始值0和他的下标-1(这是大多数前缀和的题都需要做的初始化),当遍历完前两个元素0(-1)和1之后,此时又得到这个prefix sum = 0,此时去看一下i - map.get(sum)的值是否能更大,以得出这个最长的子数组的长度。
时间O(n)
空间O(n)
Java实现
1 class Solution { 2 public int findMaxLength(int[] nums) { 3 int res = 0; 4 int sum = 0; 5 HashMap<Integer, Integer> map = new HashMap<>(); 6 map.put(0, -1); 7 for (int i = 0; i < nums.length; i++) { 8 sum += (nums[i] == 1 ? 1 : -1); 9 if (map.containsKey(sum)) { 10 res = Math.max(res, i - map.get(sum)); 11 } else { 12 map.put(sum, i); 13 } 14 } 15 return res; 16 } 17 }
JavaScript实现
1 /** 2 * @param {number[]} nums 3 * @return {number} 4 */ 5 var findMaxLength = function(nums) { 6 let map = new Map(); 7 map.set(0, -1); 8 let res = 0; 9 let sum = 0; 10 11 for (let i = 0; i < nums.length; i++) { 12 sum += nums[i] == 0 ? -1 : 1; 13 if (map.has(sum)) { 14 res = Math.max(res, i - map.get(sum)); 15 } else { 16 map.set(sum, i); 17 } 18 } 19 return res; 20 };