1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| class Solution { public int findMaxLength(int[] nums) { int ans = 0, sum = 0; Map<Integer, Integer> map = new HashMap<>(); map.put(0, -1); for (int i = 0; i < nums.length; ++i) { sum += nums[i] == 1 ? 1 : -1; if (map.containsKey(sum)) { int preIndex = map.get(sum); ans = Math.max(ans, i - preIndex); } else { map.put(sum, i); } } return ans; } }
|