leetcode之连续数组(C++)

参考链接

  1. https://leetcode-cn.com/problems/contiguous-array/
  2. 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;
    }
};
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值