Description#
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 either 0
or 1
.
Solutions#
Solution 1#
1
2
3
4
5
6
7
8
9
10
11
| class Solution:
def findMaxLength(self, nums: List[int]) -> int:
s = ans = 0
mp = {0: -1}
for i, v in enumerate(nums):
s += 1 if v == 1 else -1
if s in mp:
ans = max(ans, i - mp[s])
else:
mp[s] = i
return ans
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
| class Solution {
public int findMaxLength(int[] nums) {
Map<Integer, Integer> mp = new HashMap<>();
mp.put(0, -1);
int s = 0, ans = 0;
for (int i = 0; i < nums.length; ++i) {
s += nums[i] == 1 ? 1 : -1;
if (mp.containsKey(s)) {
ans = Math.max(ans, i - mp.get(s));
} else {
mp.put(s, i);
}
}
return ans;
}
}
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
| class Solution {
public:
int findMaxLength(vector<int>& nums) {
unordered_map<int, int> mp;
int s = 0, ans = 0;
mp[0] = -1;
for (int i = 0; i < nums.size(); ++i) {
s += nums[i] == 1 ? 1 : -1;
if (mp.count(s))
ans = max(ans, i - mp[s]);
else
mp[s] = i;
}
return ans;
}
};
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
| func findMaxLength(nums []int) int {
mp := map[int]int{0: -1}
s, ans := 0, 0
for i, v := range nums {
if v == 0 {
v = -1
}
s += v
if j, ok := mp[s]; ok {
ans = max(ans, i-j)
} else {
mp[s] = i
}
}
return ans
}
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
| /**
* @param {number[]} nums
* @return {number}
*/
var findMaxLength = function (nums) {
const mp = new Map();
mp.set(0, -1);
let s = 0;
let ans = 0;
for (let i = 0; i < nums.length; ++i) {
s += nums[i] == 0 ? -1 : 1;
if (mp.has(s)) ans = Math.max(ans, i - mp.get(s));
else mp.set(s, i);
}
return ans;
};
|