【題解】LeetCode 525. Contiguous Array

【題目敘述】https://leetcode.com/problems/contiguous-array/

class Solution {
public:
    int findMaxLength(vector<int>& nums) {
        int sz = nums.size(), ans = 0;
        map <int, int> mp;
        int p[sz+5];
        p[0] = 0;
        mp[0] = 0;
        for (int i = 1; i <= sz; i++){
            if (nums[i-1] == 1) p[i] = p[i-1]+1;
            else p[i] = p[i-1]-1;
            if (mp.count(p[i])) ans = max(ans, i-mp[p[i]]);
            else mp[p[i]] = i;
        }
        return ans;
    }
};
分享本文 Share with friends