994 · Contiguous Array
Algorithms
Medium
Description
Given a binary array, find the maximum length of a contiguous subarray with equal number of 0 and 1.
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 contiguous subarray with equal number of 0 and 1.
解法1:用presums数组。注意可以把0变成-1, 并利用hashmap,这样只要有两个presum是一样的就肯定是相同的0和1。注意hashmap里面存的对应的index是第一次出现的presum的index。
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();
vector<int> presums(n + 1, 0);
map<int, int> mp; //presums, index
int res = 0;
mp[0] = 0;
for (int i = 1; i <= n; i++) {
presums[i] = presums[i - 1] + (nums[i - 1] == 0 ? -1 : 1);
if (mp.find(presums[i]) == mp.end()) {
mp[presums[i]] = i;
} else {
res = max(res, i - mp[presums[i]]);
}
}
return res;
}
};