题目描述:
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.
Note: The length of the given binary array will not exceed 50,000.
class Solution {
public:
int findMaxLength(vector<int>& nums) {
unordered_map<int,int> hash;
hash[0]=-1;
int prefix_sum=0;
int max_length=0;
for(int i=0;i<nums.size();i++)
{ // 遇到0减一,遇到1加一,那么一段子数组中0和1个数相等的话,它的前缀和为0
prefix_sum+=(nums[i]==0?-1:1);
if(hash.count(prefix_sum))
max_length=max(max_length, i-hash[prefix_sum]);
else hash[prefix_sum]=i;
}
return max_length;
}
};
本文介绍了一种高效算法,用于在二进制数组中找到包含相同数量0和1的最长连续子数组。通过使用前缀和与哈希表,算法能够快速定位满足条件的子数组,提供了一个优雅的解决方案。
351

被折叠的 条评论
为什么被折叠?



