994 · Contiguous Array
Algorithms
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
这题应该是不能用滑动窗口做的。我试了很久,发现不行。不知道有没有高人能用滑动窗口做出来。
解法1:用presum + hashmap
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();
if (n == 0) return 0;
unordered_map<int, int> um; //<presum, pos>
vector<int> presums(n + 1, 0);
int res = 0;
um[0] = 0;
for (int i = 1; i <= n; i++) {
presums[i] = presums[i - 1] + (nums[i - 1] == 0 ? -1 : 1);
if (um.find(presums[i]) == um.end()) {
um[presums[i]] = i;
} else {
res = max(res, i - um[presums[i]]);
}
}
return res;
}
};
文章讨论了解决给定二进制数组中最长等零一连续子数组的问题,指出常规滑动窗口方法不可行,提出使用presum和哈希映射的解决方案。
1289

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



