Given a binary array, find the maximum length of a contiguous subarray with equal number of 0 and 1.html
Example 1:git
Input: [0,1] Output: 2 Explanation: [0, 1] is the longest contiguous subarray with equal number of 0 and 1.
Example 2:github
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的个数相等。对于求子数组的问题,咱们须要时刻记着求累积和是一种很犀利的工具,可是这里怎么将子数组的和跟0和1的个数之间产生联系呢?咱们须要用到一个 trick,遇到1就加1,遇到0,就减1,这样若是某个子数组和为0,就说明0和1的个数相等,这个想法真是太叼了,不过博主木有想出来。知道了这一点,咱们用一个 HashMap 创建子数组之和跟结尾位置的坐标之间的映射。若是某个子数组之和在 HashMap 里存在了,说明当前子数组减去 HashMap 中存的那个子数字,获得的结果是中间一段子数组之和,必然为0,说明0和1的个数相等,咱们更新结果 res。注意咱们须要在 HashMap 初始化一个 0 -> -1 的映射,这是为了当 sum 第一次出现0的时候,即这个子数组是从原数组的起始位置开始,咱们须要计算这个子数组的长度,而不是创建当前子数组之和 sum 和其结束位置之间的映射。好比就拿例子1来讲,nums = [0, 1],当遍历0的时候,sum = -1,此时创建 -1 -> 0 的映射,当遍历到1的时候,此时 sum = 0 了,若 HashMap 中没有初始化一个 0 -> -1 的映射,咱们此时会创建 0 -> 1 的映射,而不是去更新这个知足题意的子数组的长度,因此要这么初始化,参见代码以下:工具
解法一:post
class Solution { public: int findMaxLength(vector<int>& nums) { int res = 0, n = nums.size(), sum = 0; unordered_map<int, int> m{{0, -1}}; for (int i = 0; i < n; ++i) { sum += (nums[i] == 1) ? 1 : -1; if (m.count(sum)) { res = max(res, i - m[sum]); } else { m[sum] = i; } } return res; } };
下面这种方法跟上面的解法基本上彻底同样,只不过在求累积和的时候没有用条件判断,而是用了一个很叼的等式直接包括了两种状况,参见代码以下:url
解法二:spa
class Solution { public: int findMaxLength(vector<int>& nums) { int res = 0, n = nums.size(), sum = 0; unordered_map<int, int> m{{0, -1}}; for (int i = 0; i < n; ++i) { sum += (nums[i] << 1) -1; if (m.count(sum)) { res = max(res, i - m[sum]); } else { m[sum] = i; } } return res; } };
Github 同步地址:code
https://github.com/grandyang/leetcode/issues/525htm
相似题目:
Maximum Size Subarray Sum Equals k
参考资料:
https://leetcode.com/problems/contiguous-array/