1. 程式人生 > >994.Contiguous Array 鄰近陣列

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;
    }
};