连续数组,

1、描述

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

示例 1:

输入: nums = [0,1]
输出: 2
说明: [0, 1] 是具有相同数量0和1的最长连续子数组。

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

2、关键字,

数组,最长,相同,

3、思路

前缀和统计出现的次数,
把0转成-1,一起计算,
使用hash保存次数,

4、notes

以后见到0和1就想着变成+1,和-1吧

5、复杂度

时间:O(N)
空间:O(n)小于等于n

6、code

使用两行n列的数组存起来,然后再两层循环遍历统计,又会时间超限制,

// 0变-1,再使用前缀和,
//使用hash存起来
class Solution {
public:
    int findMaxLength(vector<int>& nums) {
        int n = nums.size();
        int res =0;
        if(n<2) return 0;
        unordered_map<int,int>mp;  // 保存第一次 出现的数字 到下标位置的hash
        mp[0] = -1;
        int counter = 0;  // 是1就加1,是0就减一
        for(int i = 0;i < n; i++){            
            if(nums[i] > 0){  // 如果是 1
                counter++;              
            }else{
                counter--;
            }

            if(mp.count(counter)){  // 之间有没有出现过,如果出现过,就有机会是结果,
                res = max(res,i -mp[counter]);
            }
            else{
                mp[counter] = i;  // 没出现过,就存进来。
            }
            
        }

        return res;
    }
};


/

//方法二


class Solution {
public:
    int findMaxLength(vector<int>& nums) {
        int n = nums.size();
        if(n<2) return 0;
        vector<vector<int>>countmy(2,vector<int>(n,0));      
        int res = 0;

        if(nums[0] == 0){
                    countmy[0][0] = 1;
                    countmy[1][0] = 0;
                }
        else{
                countmy[1][0] = 1;
                countmy[0][0] = 0;
            }

        for(int i = 1;i < n; i++){
                      
                if(nums[i] == 0){
                   
                    countmy[0][i] = 1 + countmy[0][i-1];
                    countmy[1][i] = countmy[1][i-1];  // 
                }
                else{
                    countmy[1][i] = 1 + countmy[1][i-1];
                    countmy[0][i] = countmy[0][i-1];  //
                }

                if(countmy[0][i] == countmy[1][i]){
                res = max(res,i+1);
                }  
        }     
        for(int i = 1;i < n;i++){
            for(int j = 0; j < i;j++){
                if(countmy[0][i] - countmy[0][j] ==countmy[1][i] - countmy[1][j]){
                    res = max(res,i - j );
                }
            }
        }
        return res;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值