525. Contiguous Array

Given a binary array nums, return the maximum length of a contiguous subarray with an equal number of 0 and1.

Example 1:

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

Example 2:

Input: nums = [0,1,0] Output: 2 Explanation: [0, 1] (or [1, 0]) is a longest contiguous subarray with equal number of 0 and 1.

Constraints:

  • 1 <= nums.length <= 105
  • nums[i] is either 0 or 1.
class Solution {
public:
    int findMaxLength(vector<int>& nums) {
        int res = 0;
        int n = nums.size();
        int sum = 0;
        unordered_map<int, int> m{{0, -1}};
        for (int i = 0; i < n; ++i) {
            // 遇到 1 就 +1,遇到 0 就 -1
            sum += (nums[i] == 1) ? 1 : -1;
            // 如果加起來的總和不等於 0 的話
            // 目前的長度為目前的 index i 減掉 m[sum]
            if (m.count(sum)) {
                res = max(res, i - m[sum]);
            } else {
                // 如果加起來的總和等於 0 的話,其值為目前的 index
                m[sum] = i;
            }
        }
        // nums = [0,1,0]
        // m = {{-1: 0}, {0: -1}}

        // nums = [0, 0, 0, 1, 1, 1]
        // m = {{-2: 1}, {-1: 0}, {-3: 2}, {0: -1}}
        return res;
    }
};
  • T: O(N)O(N)
  • S: O(N)O(N)