comments | difficulty | edit_url | tags | |||
---|---|---|---|---|---|---|
true |
Medium |
|
Given a binary array nums
, return the maximum length of a contiguous subarray with an equal number of 0
and 1
.
Example 1:
Input: nums = [0,1] Output: 2 Explanation: [0, 1] is the longest contiguous subarray with an equal number of 0 and 1.
Example 2:
Input: nums = [0,1,0] Output: 2 Explanation: [0, 1] (or [1, 0]) is a longest contiguous subarray with equal number of 0 and 1.
Constraints:
1 <= nums.length <= 105
nums[i]
is either0
or1
.
According to the problem description, we can treat $0$s in the array as
We use a hash table to store all prefix sums and their first occurrence indices. Initially, we map the prefix sum of
As we iterate through the array, we calculate the prefix sum
The time complexity is
class Solution:
def findMaxLength(self, nums: List[int]) -> int:
d = {0: -1}
ans = s = 0
for i, x in enumerate(nums):
s += 1 if x else -1
if s in d:
ans = max(ans, i - d[s])
else:
d[s] = i
return ans
class Solution {
public int findMaxLength(int[] nums) {
Map<Integer, Integer> d = new HashMap<>();
d.put(0, -1);
int ans = 0, s = 0;
for (int i = 0; i < nums.length; ++i) {
s += nums[i] == 1 ? 1 : -1;
if (d.containsKey(s)) {
ans = Math.max(ans, i - d.get(s));
} else {
d.put(s, i);
}
}
return ans;
}
}
class Solution {
public:
int findMaxLength(vector<int>& nums) {
unordered_map<int, int> d{{0, -1}};
int ans = 0, s = 0;
for (int i = 0; i < nums.size(); ++i) {
s += nums[i] ? 1 : -1;
if (d.contains(s)) {
ans = max(ans, i - d[s]);
} else {
d[s] = i;
}
}
return ans;
}
};
func findMaxLength(nums []int) int {
d := map[int]int{0: -1}
ans, s := 0, 0
for i, x := range nums {
if x == 0 {
x = -1
}
s += x
if j, ok := d[s]; ok {
ans = max(ans, i-j)
} else {
d[s] = i
}
}
return ans
}
function findMaxLength(nums: number[]): number {
const d: Record<number, number> = { 0: -1 };
let ans = 0;
let s = 0;
for (let i = 0; i < nums.length; ++i) {
s += nums[i] ? 1 : -1;
if (d.hasOwnProperty(s)) {
ans = Math.max(ans, i - d[s]);
} else {
d[s] = i;
}
}
return ans;
}
/**
* @param {number[]} nums
* @return {number}
*/
var findMaxLength = function (nums) {
const d = { 0: -1 };
let ans = 0;
let s = 0;
for (let i = 0; i < nums.length; ++i) {
s += nums[i] ? 1 : -1;
if (d.hasOwnProperty(s)) {
ans = Math.max(ans, i - d[s]);
} else {
d[s] = i;
}
}
return ans;
};