
记录每个位置的1和0的差的个数,如果以前出现过这个数,那么答案有可能就是二者的差。
class Solution {
public:
int findMaxLength(vector<int>& nums) {
int maxLength = 0;
unordered_map<int, int> mp;
int cnt = 0;
mp[cnt] = -1;
int i = 0;
for (int x : nums) {
cnt += x == 1 ? 1 : -1;
if (mp.count(cnt)) maxLength = max(maxLength, i - mp[cnt]);
else mp[cnt] = i;
i++;
}
return maxLength;
}
};