参考链接
- https://leetcode-cn.com/problems/contiguous-array/
- https://leetcode-cn.com/problems/contiguous-array/solution/lian-xu-shu-zu-by-leetcode-solution-mvnm/
题目描述
给定一个二进制数组 nums , 找到含有相同数量的 0 和 1 的最长连续子数组,并返回该子数组的长度。
解题思路
依然可以转化为前缀和的思路。比如,分别记录索引i以前0和1的个数,对于子数组[i, j]而言,如果其具有相同数量的0和1,那么索引i以前的0和1的个数差与索引j以前的0和1的个数差应该一样。我们可以用哈希表建立差值到索引的映射,如果遇到相同的差值,那么索引差即为满足条件的数组的长度,取它们的最大值即可。
另一种更巧的想法是,将0视为-1,这样问题转化为寻找元素和为0的连续子数组。进一步地,如果子数组[i, j]的和为0,那么子数组[0, i-1]与[0, j]的和是一样的。实现过程中只需要一个变量保存当前索引及以前元素的和,另外也需要一个哈希表建立和与索引的映射,如果遇到相同的和,那么索引差即为满足条件的数组的长度,取它们的最大值即可。
代码
思路1
class Solution {
public:
int findMaxLength(vector<int>& nums) {
nums.push_back(-1);
int nums_0 = 0;
int nums_1 = 0;
int res = 0;
unordered_map<int, int> mp;
for (int i = 0; i < nums.size(); i ++)
{
if (mp.count(nums_0 - nums_1))
{
int pre = mp[nums_0 - nums_1];
res = max(res, i - pre);
}
else
{
mp[nums_0 - nums_1] = i;
}
if (nums[i] == 0)
{
nums_0 += 1;
}
else
{
nums_1 += 1;
}
}
return res;
}
};
思路2
class Solution {
public:
int findMaxLength(vector<int>& nums) {
int maxLength = 0;
unordered_map<int, int> mp;
int counter = 0;
mp[counter] = -1;
int n = nums.size();
for (int i = 0; i < n; i++)
{
int num = nums[i];
if (num == 1)
{
counter++;
}
else
{
counter--;
}
if (mp.count(counter))
{
int prevIndex = mp[counter];
maxLength = max(maxLength, i - prevIndex);
}
else
{
mp[counter] = i;
}
}
return maxLength;
}
};