Leetcode 525 连续数组 前缀和 + 哈希
作者:互联网
class Solution {
public:
int findMaxLength(vector<int>& nums) {
int n = nums.size();
vector<int> sum(n+1);
for(int i = 1; i <= n; i++) sum[i] = sum[i-1] + (nums[i-1] ? 1 : -1);
unordered_map<int,int> hash;
int res = 0;
hash[0] = 0;
for(int i = 1; i <= n; i++)
{
if(hash.find(sum[i]) != hash.end()) res = max(res, i - hash[sum[i]]);
else hash[sum[i]] = i;
}
return res;
}
};
标签:hash,nums,int,res,sum,525,vector,哈希,Leetcode 来源: https://blog.csdn.net/Edviv/article/details/117536082