[LeetCode] 525. Contiguous Array

Given a binary array nums, return the maximum length of a contiguous subarray with an equal number of 0 and 1.

Example 1:
Input: nums = [0,1]
Output: 2
Explanation: [0, 1] is the longest contiguous subarray with an equal number of 0 and 1.

Example 2:
Input: nums = [0,1,0]
Output: 2
Explanation: [0, 1] (or [1, 0]) is a longest contiguous subarray with equal number of 0 and 1.

Constraints:
1 <= nums.length <= 105
nums[i] is either 0 or 1.

连续数组。

给定一个二进制数组 nums , 找到含有相同数量的 0 和 1 的最长连续子数组,并返回该子数组的长度。

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/contiguous-array
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

思路

这个题目看似简单但是这个思路比较难想到。这个题的 tag 是 hash table,感觉可以往前缀和为 0 的思路上去靠。题目问的是包含相同数量的 0 和 1 的子数组的长度,这里我们需要灵活运用前缀和这个思路。如果把 0 替换成 -1,也就把题目转化为满足条件的子数组的和会是 0,因为 -1 和 1 是成对出现的。所以做法是创建一个 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实现

class Solution {
	public int findMaxLength(int[] nums) {
		int res = 0;
		int sum = 0;
		HashMap<Integer, Integer> map = new HashMap<>();
		map.put(0, -1);
		for (int i = 0; i < nums.length; i++) {
			sum += (nums[i] == 1 ? 1 : -1);
			if (map.containsKey(sum)) {
				res = Math.max(res, i - map.get(sum));
			} else {
				map.put(sum, i);
			}
		}
		return res;
	}
}

JavaScript实现

/**
 * @param {number[]} nums
 * @return {number}
 */
var findMaxLength = function(nums) {
    let map = new Map();
    map.set(0, -1);
    let res = 0;
    let sum = 0;

    for (let i = 0; i < nums.length; i++) {
        sum += nums[i] == 0 ? -1 : 1;
        if (map.has(sum)) {
            res = Math.max(res, i - map.get(sum));
        } else {
            map.set(sum, i);
        }
    }
    return res;
};
posted @ 2020-04-14 10:12  CNoodle  阅读(234)  评论(0)    收藏  举报