题目描述(传送门)
给定一个二进制数组 nums , 找到含有相同数量的 0 和 1 的最长连续子数组,并返回该子数组的长度。
示例 1:
输入: nums = [0,1]
输出: 2
说明: [0, 1] 是具有相同数量 0 和 1 的最长连续子数组。
示例 2:
输入: nums = [0,1,0]
输出: 2
说明: [0, 1] (或 [1, 0]) 是具有相同数量0和1的最长连续子数组。
解题思路
暴力(超时)
public int findMaxLength(int[] nums) {
int max = 0;
for (int i = 0; i < nums.length; i++) {
int sum = nums[i];
for (int j = i+1; j < nums.length; j++) {
sum += nums[j];
if (sum * 2 == (j - i + 1)) {
max = Math.max(max, j - i + 1);
}
}
}
return max;
}
前缀和
- 利用前缀和count ,遇到 0 时减一,遇到 1 时加一,把前缀和 count 和下标 i 存入哈希表中。
- 如果当前 count 在哈希表中存在,则说明 当前下标 i 到 count 第一次出现的下标(在哈希表中对应的value),这个范围内,0 和 1出现次数相同,因为这个范围内的前缀和为 0 ,迭代最大长度ans 。
- 最后返回ans
public int findMaxLength(int[] nums) {
Map<Integer, Integer> map = new HashMap<>();
map.put(0, -1);
int ans = 0;
int count = 0;
for (int i = 0; i < nums.length; i++) {
if (nums[i] == 1) {
count++;
} else {
count--;
}
if (map.containsKey(count)) {
int prevIndex = map.get(count);
ans = Math.max(ans, i - prevIndex);
} else {
map.put(count, i);
}
}
return ans;
}