My C++ solution using map


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

Log in to reply
 

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