525. Contiguous Array
class Solution { public int findMaxLength(int[] nums) { for(int i = 0; i < nums.length; i++){ if(nums[i] == 0){ nums[i] = -1; } } int[] prefix = new int[nums.length + 1]; prefix[0] = 0; for(int i = 1; i < prefix.length; i++){ prefix[i] = prefix[i-1] + nums[i-1]; } HashMap<Integer, Integer> map = new HashMap<>(); int count = 0; for(int i = 0; i < prefix.length; i++){ if(!map.containsKey(prefix[i])){ map.put(prefix[i], i); }else{ int index = map.get(prefix[i]); count = Math.max(count, i - index); } } return count; } }
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.
posted on 2018-07-18 09:04 猪猪🐷 阅读(123) 评论(0) 收藏 举报
浙公网安备 33010602011771号