Lintcode 994 · Contiguous Array (presum + hashmap好题

994 · Contiguous Array
Algorithms

The length of the given binary array will not exceed 50,000.

Example
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

这题应该是不能用滑动窗口做的。我试了很久,发现不行。不知道有没有高人能用滑动窗口做出来。

解法1:用presum + hashmap

class Solution {
public:
    /**
     * @param nums: a binary array
     * @return: the maximum length of a contiguous subarray
     */
    int findMaxLength(vector<int> &nums) {
        int n = nums.size();
        if (n == 0) return 0;
        unordered_map<int, int> um; //
        vector<int> presums(n + 1, 0);
        int res = 0;
        um[0] = 0;
        for (int i = 1; i <= n; i++) {
            presums[i] = presums[i - 1] + (nums[i - 1] == 0 ? -1 : 1);
            if (um.find(presums[i]) == um.end()) {
                um[presums[i]] = i;
            } else {
                res = max(res, i - um[presums[i]]);
            }
        }

        return res;
    }
};

你可能感兴趣的:(数据结构,leetcode,算法)