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,00

class Solution {
public:
    //hash表。o(N)的时间复杂度
    //0 1 0 1 0 0 1 1 
    //可以这样考虑 每次遇到0。count就减1,每次遇到1count就加1
    //这样,当往后扫描时,下一次再遇到这个count时,这两个位置之间的0和1就是相等的
    int findMaxLength(vector<int>& nums) {
        map<int,int> m;
        int count = 0, res=0;
        m[count] = 0;
        for(int i=0;i<nums.size();i++){
            if(nums[i] == 0){
                count--;
            }else{
                count++;
            }
            if(m.find(count) != m.end()){
                res = max(res,i+1 - m[count]);
            }else{
                m[count] = i+1;
            }
        }
        return res;
    }
};
原文地址:https://www.cnblogs.com/wsw-seu/p/13363057.html