0%

leetcode-day-13

LeetCode 30 days Challenge - Day 13

本系列将对LeetCode新推出的30天算法挑战进行总结记录,旨在记录学习成果、方便未来查阅,同时望为广大网友提供帮助。


Contiguous Array

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

Example 1:

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

Example 2:

1
2
3
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.


Solution

题目要求分析:给定一个只包含0或1的数组,求满足条件(子数组中0和1数量相等)的最长连续子数组的长度。

解法:

本题关键是遍历数组,确保不漏掉符合条件的子数组,并更新最大长度。

这里为了减少空间复杂度,使用哈希结构建立count(初始为0,遇0减1,遇1加1)到pos(count第一次出现的位置)的映射:

  1. 初始化res为最大长度,count为当前1和0的个数差,负数表示0比1多。
  2. 建立映射,初始化m[0] = -1的意义是:无论第一个元素是0还是1,count都将变为非0,因此,count=0首次出现的位置实际上是-1处(不存在,只是虚拟出一个位置,以保证当最长子数组包含第一个元素的时候,能正确计算长度)。
  3. 在遍历过程中:
    1. m.find(count) == m.end()即新的count值首次出现,记录其位置。
    2. 反之,更新res为较大值。

以下提供参考图片供读者理解:


1
2
3
4
5
6
7
8
9
10
11
int findMaxLength(vector<int>& nums) {
int res = 0, count = 0;
unordered_map<int, int> m;
m[0] = -1;
for (int i = 0; i < nums.size(); i++) {
count += nums[i] ? 1 : -1;
if (m.find(count) == m.end()) m[count] = i;
else res = max(res, i - m[count]);
}
return res;
}

传送门:Contiguous Array

Karl