其他分享
首页 > 其他分享> > 【LeetCode】525. 连续数组

【LeetCode】525. 连续数组

作者:互联网

class Solution {
public:
    int findMaxLength(vector<int>& nums) {
        int maxLength=0,counter=0,pre,temp;
        unordered_map<int,int> mp;   //hash表存储的是counter每个取值第一次出现的下标
        //如果counter的值在哈希表中已经存在,则取出counter在哈希表中的下标,并更新最长子数组的长度
        //如果counter的值不存在,则将当前余数和当前下标i的值存入hash表中

        int n=nums.size();
        mp[0]=-1;    //空的前缀下标为-1

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

            if(mp.count(counter))
            {
                pre=mp[counter];
                temp=i-pre;   //i-(pre+1)+1
                if(temp>maxLength)
                    maxLength=temp;
            }
            else mp[counter]=i;
        }
        return maxLength;
    }
};

 

标签:下标,int,counter,525,mp,数组,表中,maxLength,LeetCode
来源: https://www.cnblogs.com/zzxcm/p/15864633.html