leetcode題解-525. Contiguous Array
阿新 • • 發佈:2019-02-04
題目: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: Input: [0,1,0] Output: 2
Explanation: [0, 1] (or [1, 0]) is a longest contiguous subarray with equal number of 0 and 1.
這個題目好像是新出的,其實我一看到這個題的時候思路有點亂,一直沒有理清楚0和1應該怎麼去處理他們的關係才能保證得到正確的答案。然後去看了一下discuss,下面記錄一下。
方法一,使用一個數組diff[]來記錄當前位置之前所有出現的1減去所有的0。然後使用map來儲存diff[i]與其索引i。這樣的話每當diff[j] == diff[i]時,就意味著i到j之間是一個滿足條件的子陣列。這種方法擊敗了65%的使用者。程式碼入下:
public int findMaxLength(int[] nums) {
int res = 0;
Map<Integer, Integer> map = new HashMap<>();
int n = nums.length;
int [] diff = new int[n+1];
map.put(0, 0);
for(int i=1; i<=n; i++){
diff[i] = diff[i-1] + (nums[i-1] == 0 ? -1 : 1);
if(!map.containsKey(diff[i]))
map.put(diff[i], i);
else
res = Math.max(res, i-map.get(diff[i]));
}
return res;
}
方法二,思路類似,也是使用map來記錄之前遍歷過的陣列資訊,這種方法擊敗了95.7%的使用者。程式碼入下:
public int findMaxLength2(int[] nums) {
Map<Integer, Integer> map = new HashMap<Integer, Integer>() {{put(0,0);}};
int maxLength = 0, runningSum = 0;
for (int i=0;i<nums.length;i++) {
runningSum += nums[i];
Integer prev = map.get(2*runningSum-i-1);
if (prev != null) maxLength = Math.max(maxLength, i+1-prev);
else map.put(2*runningSum-i-1, i+1);
}
return maxLength;
}