版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zhaohaibo_/article/details/85806438
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
class Solution {
public:
int findMaxLength(vector<int>& nums) {
// 哈希表记录 上一个前缀和等于s的区间 的初始下标
unordered_map<int, int> hash;
hash[0] = -1;
int res = 0, s = 0;
for (int i = 0; i < nums.size(); i ++ ){
s += nums[i] ? 1 : -1;
if(hash.count(s)) res = max(res, i - hash[s]);
else hash[s] = i;
}
return res;
}
};