-
Notifications
You must be signed in to change notification settings - Fork 2
/
ContiguousArray.java
57 lines (51 loc) · 1.78 KB
/
ContiguousArray.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
package Leetcode;
import java.util.HashMap;
import java.util.Map;
/**
* @author kalpak
*
* 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.
*/
public class ContiguousArray {
public static int findMaxLength(int[] nums) {
int sum = 0;
int result = 0;
// To find the maximum length, we need a dict to store the value of count (as the key) and its associated index (as the value).
// We only need to save a count value and its index at the first time, when the same count values appear again,
// we use the new index subtracting the old index to calculate the length of a subarray.
// A variable max_length is used to to keep track of the current maximum length.
Map<Integer, Integer> map = new HashMap<>();
map.put(0, -1);
for(int i = 0; i < nums.length; i++) {
if(nums[i] == 0)
sum++;
else
sum--;
if(map.containsKey(sum))
result = Math.max(result, i - map.get(sum));
else
map.put(sum, i);
}
return result;
}
public static void main(String[] args) {
System.out.println(findMaxLength(new int[]{0,1,0}));
System.out.println(findMaxLength(new int[]{1}));
System.out.println(findMaxLength(new int[]{0}));
System.out.println(findMaxLength(new int[]{1,1}));
}
}