|
22 | 22 | */
|
23 | 23 | public class _525 {
|
24 | 24 |
|
25 |
| - //credit: https://leetcode.com/articles/contiguous-array/#approach-3-using-hashmap-accepted |
26 |
| - public int findMaxLength(int[] nums) { |
27 |
| - if (nums == null || nums.length == 0) { |
28 |
| - return 0; |
29 |
| - } |
30 |
| - int count = 0; |
31 |
| - int max = 0; |
32 |
| - Map<Integer, Integer> map = new HashMap(); |
33 |
| - map.put(0, -1);//initialize the map, which means at index zero, the length of contiguous subarray is -1 |
34 |
| - for (int i = 0; i < nums.length; i++) { |
35 |
| - count += nums[i] == 1 ? 1 : -1; |
36 |
| - if (map.containsKey(count)) { |
37 |
| - max = Math.max(i - map.get(count), max); |
38 |
| - } else { |
39 |
| - map.put(count, i);//only when the map does not have this key, we put it in the map, this avoids overwriting the map |
40 |
| - //also, it helps us keep the most leftside value in the map to help us compute the longest contigous array length |
| 25 | + public static class Solution1 { |
| 26 | + //credit: https://leetcode.com/articles/contiguous-array/#approach-3-using-hashmap-accepted |
| 27 | + public int findMaxLength(int[] nums) { |
| 28 | + if (nums == null || nums.length == 0) { |
| 29 | + return 0; |
| 30 | + } |
| 31 | + int count = 0; |
| 32 | + int max = 0; |
| 33 | + Map<Integer, Integer> map = new HashMap(); |
| 34 | + map.put(0, -1);//initialize the map, which means at index zero, the length of contiguous subarray is -1 |
| 35 | + for (int i = 0; i < nums.length; i++) { |
| 36 | + count += nums[i] == 1 ? 1 : -1; |
| 37 | + if (map.containsKey(count)) { |
| 38 | + max = Math.max(i - map.get(count), max); |
| 39 | + } else { |
| 40 | + map.put(count, i);//only when the map does not have this key, we put it in the map, this avoids overwriting the map |
| 41 | + //also, it helps us keep the most leftside value in the map to help us compute the longest contigous array length |
| 42 | + } |
41 | 43 | }
|
| 44 | + return max; |
42 | 45 | }
|
43 |
| - return max; |
44 | 46 | }
|
45 |
| - |
46 | 47 | }
|
0 commit comments