問題:java
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: 2 Explanation: [0, 1] is the longest contiguous subarray with equal number of 0 and 1.
Example 2:spa
Input: [0,1,0] Output: 2 Explanation: [0, 1] (or [1, 0]) is a longest contiguous subarray with equal number of 0 and 1.
Note: The length of the given binary array will not exceed 50,000.code
解決:https://discuss.leetcode.com/topic/79906/easy-java-o-n-solution-presum-hashmapleetcode
① 找到最長的包含0,1(或1,0)的子串,讓咱們找相鄰的子數組使其0和1的個數相等。對於求子數組的問題,咱們須要時刻記着求累積和是一種很犀利的工具,可是這裏怎麼將子數組的和跟0和1的個數之間產生聯繫呢?咱們須要用到一個trick,遇到1就加1,遇到0,就減1,這樣若是某個子數組和爲0,就說明0和1的個數相等。知道了這一點,咱們用一個哈希表創建子數組之和跟結尾位置的座標之間的映射。若是某個子數組之和在哈希表裏存在了,說明當前子數組減去哈希表中存的那個子數字,獲得的結果是中間一段子數組之和,必然爲0,說明0和1的個數相等,咱們更新結果res。。。get
class Solution { //102ms
public int findMaxLength(int[] nums) {
for (int i = 0;i < nums.length;i ++){
if (nums[i] == 0) nums[i] = -1;
}
Map<Integer,Integer> map = new HashMap<>();
map.put(0,-1);
int sum = 0;
int max = 0;
for (int i = 0;i < nums.length;i ++){
sum += nums[i];
if (map.containsKey(sum)){
max = Math.max(max,i - map.get(sum));
}else {
map.put(sum,i);
}
}
return max;
}
}hash
② 在discuss中看到的。it
class Solution { //45ms
public int findMaxLength(int[] nums) {
if (nums == null || nums.length == 0) return 0;
int[] map = new int[(2*nums.length) + 1];
Arrays.fill(map, -2);
map[nums.length] = -1;
int max = 0;
int sum = 0;
for (int i = 0;i < nums.length;i ++) {
sum = sum + (nums[i] == 0 ? -1 : 1);
if (map[sum + nums.length] >= -1) {
max = Math.max(max, i - map[sum + nums.length]);
} else {
map[sum + nums.length] = i;
}
}
return max;
}
}io