Contiguous Array

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.

Note: The length of the given binary array will not exceed 50,000.

 1 public class Solution {
 2     public int findMaxLength(int[] nums) {
 3         if (nums == null) return 0;
 4         int sum = 0, n = nums.length, maxLength = 0;
 5         HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
 6         for (int i = 0; i < n; i++) {
 7             sum += nums[i] == 1 ? 1 : -1;
 8             if (sum == 0) maxLength = i + 1;
 9             else {
10                 if (map.containsKey(sum))
11                     maxLength = Math.max(maxLength, i - map.get(sum));
12                 else
13                     map.put(sum, i);
14             }
15         }
16         return maxLength;
17     }
18 }
原文地址:https://www.cnblogs.com/amazingzoe/p/6733173.html