Concise C++ O(n) Solution. (unordered_map + one pass)


  • 0
    class Solution {
    public:
        int findMaxLength(vector<int>& nums) {
            unordered_map<int, int> sums;
            sums[0] = -1;
            int sum = 0, len = 0;
            for (int i = 0; i < nums.size(); i++) {
                sum += nums[i] ? 1 : -1;
                if (sums.find(sum) != sums.end()) {
                    len = max(len, i - sums[sum]);
                }
                else sums[sum] = i;
            }
            return len;
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.