LeetCode 525: Continuous Array
阿新 • • 發佈:2017-09-03
etc a star sta div .get mmap blog tin star
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; } }
LeetCode 525: Continuous Array