LeetCode 525. Contiguous Array
525. Contiguous Array
Description Submission Solutions
- Total Accepted: 2476
- Total Submissions: 8220
- Difficulty: Medium
- Contributors: bishwa
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.
Subscribe to see which companies asked this question.
【题目分析】
这个题目的意思是给定一个只包含0,1的整数数组,找到数组中最长的一个子序列,该序列中1的个数和0的个数相同。
【思路】
这个题目真的很有意思啊,我感觉自己想不到这么好的解法。
看大家的解题思路如下:
The idea is to change 0
in the original array to -1
. Thus, if we find SUM[i, j] == 0
then we know there are even number of -1
and 1
between index i
and j
. Also put the sum
to index
mapping to a HashMap to make search faster.
【java代码】
1 public class Solution { 2 public int findMaxLength(int[] nums) { 3 for(int i = 0; i < nums.length; i++) { 4 if(nums[i] == 0) nums[i] = -1; 5 } 6 7 int res = 0, sum = 0; 8 Map<Integer, Integer> map = new HashMap<>(); 9 map.put(0, -1); 10 11 for(int i = 0; i < nums.length; i++) { 12 sum += nums[i]; 13 if(map.containsKey(sum)) { 14 res = Math.max(res, i-map.get(sum)); 15 } 16 else { 17 map.put(sum, i); 18 } 19 } 20 21 return res; 22 } 23 }