994.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个数相等的子数组的长度。
这里用到一个sum,遇到1就加1,遇到0就减1,这样就会得到每个角标下的sum。
哈希表建立sum值和角标之间的映射。
遍历num成员计算sum值,如果哈希表中存在该sum值,就用当前角标减去哈希表中sum对应的角标,就会得到中间子数组长度,比较更新res。如果哈希表中不存在则添加该sum值和对应的角标。

class Solution {
public:
    int findMaxLength(vector<int>& nums) {
        int res = 0, n = nums.size(), sum = 0;
        unordered_map<int, int> m{{0, -1}};
        for (int i = 0; i < n; ++i) {
            sum += (nums[i] == 1) ? 1 : -1;
            if (m.count(sum)) {
                res = max(res, i - m[sum]);
            } else {
                m[sum] = i;
            }
        }
        return res;
    }
};

猜你喜欢

转载自www.cnblogs.com/narjaja/p/10031295.html