LeetCode 525. Contiguous Array

525. Contiguous Array

Given a binary array, find the maximum length of a contiguous subarray with equal number of 0 and 1.

Example 1:

Input: [0,1]
Output: 2
Explanation: [0, 1] is the longest contiguous subarray with equal number of 0 and 1.

Example 2:

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个数一样的最长子数组的长度。

解题思路:
如果我们有一个只包含0和1的数组,和一个变量count,初始值为0,我们从头开始遍历数组,遇到1的时候,count加1,遇到0的时候,count减1,如果遍历完整个数组之后,count的值为0,那么可以说明数组中含有相同的个数的0和1。但是在这里,我们要找的是子数组,我们并不知道这个子数组的的开头和结尾,但是,如果我们用同样的方法遍历一个数组,假如遍历数组[1, 1, 1, 0, 0],我们可以发现count的变化是0->1->2->3->2->1,其中count第1和第5的值为1,对应原数组[1, 5)之间的子数组是包含了相同个数的0和1的。
所以,我们可以用一个map结构,用count的值作为key,用出现这个值的位置作为val,当然这个位置我们可以只保留最开始和最后一个就可以了,最后遍历一次这个map,找到每个key的val中间隔最大的就是题目要的结果。

代码:

class Solution {
public:
    int findMaxLength(vector<int>& nums) {
        map<int, vector<int>> count2index;
        int count = 0;
        int max = 0;
        count2index.insert(pair<int, vector<int> > (0, vector<int>({-1})));
        for (int i = 0; i < nums.size(); i++) {
            count += nums[i] == 0 ? -1 : 1;
            if (count2index.find(count) == count2index.end()) {
                count2index.insert(pair<int, vector<int> > (count, vector<int>()));
            }
            count2index[count].push_back(i);
        }
        map<int, vector<int>>::iterator it = count2index.begin();
        while (it != count2index.end()) {
            int begin = *((it->second).begin());
            int end = *((it->second).end() - 1);
            if (end - begin > max) max = end - begin;
            it++;
        }
        return max;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值