[抄题]:
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: 2Explanation: [0, 1] is the longest contiguous subarray with equal number of 0 and 1.
Example 2:
Input: [0,1,0]Output: 2Explanation: [0, 1] (or [1, 0]) is a longest contiguous subarray with equal number of 0 and 1.
[暴力解法]:
时间分析:
空间分析:
[优化后]:
时间分析:
空间分析:
[奇葩输出条件]:
[奇葩corner case]:
[思维问题]:
以为要用dp,求个数
结果求和类的问题还是要用hashmap
[一句话思路]:
0,1不好弄中间值,把0改成-1后再求中间值
[输入量]:空: 正常情况:特大:特小:程序里处理到的特殊情况:异常情况(不合法不合理的输入):
[画图]:
[一刷]:
[二刷]:
[三刷]:
[四刷]:
[五刷]:
[五分钟肉眼debug的结果]:
[总结]:
0,1不好弄中间值,把0改成-1后再求中间值
[复杂度]:Time complexity: O(n) Space complexity: O(n)
[英文数据结构或算法,为什么不用别的数据结构或算法]:
[算法思想:递归/分治/贪心]:
[关键模板化代码]:
[其他解法]:
[Follow Up]:
[LC给出的题目变变变]:
[代码风格] :
class Solution { public int findMaxLength(int[] nums) { //cc if (nums == null || nums.length == 0) return 0; //ini: hashmap, 1 to -1, sum Mapmap = new HashMap<>(); map.put(0, -1); int sum = 0, max = 0; for (int i = 0; i < nums.length; i++) { if (nums[i] == 0) nums[i] = -1; } //for loop, check sum for (int i = 0; i < nums.length; i++) { sum += nums[i]; //contain or not if (map.containsKey(sum)) { max = Math.max(max, i - map.get(sum)); }else { map.put(sum, i); } } return max; }}