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.
思路:
将0改为-1,将原题目改成求最大连续区间,区间内元素和为0。用map记录当前元素 j 和之前所有元素的和与下标,当map
中存在相同的sum时,说明之前i到j的区间元素和为0。
int findMaxLength(vector<int>& nums) { for (auto& a:nums) if (a == 0)a = -1; map<int, int>mp; mp[0] = -1; int sum = 0,ret =0; for (int i = 0; i < nums.size();i++) { sum += nums[i]; if (mp.count(sum))ret = max(ret, i - mp[sum]); else mp[sum] = i; } return ret; }
参考: