Note: 1. Remember to intial (0, -1) since this kind of problems need a starting point.
class Solution { public int findMaxLength(int[] nums) { if (nums.length < 2) { return 0; } for (int i = 0; i < nums.length; i++) { if (nums[i] == 0) { nums[i] = -1; } } Map<Integer, Integer> sumMap = new HashMap<>(); sumMap.put(0, -1); int sum = 0; int result = 0; for (int i = 0; i < nums.length; i++) { sum += nums[i]; if (!sumMap.containsKey(sum)) { sumMap.put(sum, i); } else { result = Math.max(result, i - sumMap.get(sum)); } } return result; } }
时间: 2024-11-08 16:28:46