525. Contiguous Array
问题描述:
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.
解题思路:
遇到这样求自数组的问题以后可以都考虑一下累加和。
在这里我们也可以用累加和来做:
遇见1的时候sum++,遇见0的时候sum--
若此时sum == 0时, 代表从下标为0的数字到现在为止0和1的个数相同,我们可以令ret = i+1
若此时sum != 0, 我们可以在hash表中前面是否存在和为sum的子数组,若存在,则长度为 i - m[sum] 为当前满足要求的子数组的长度。
时间复杂度为O(n)空间复杂度为O(n);
代码:
class Solution { public: int findMaxLength(vector<int>& nums) { unordered_map<int, int> m; int ret = 0; int sum = 0; for(int i = 0; i < nums.size(); i++){ if(nums[i] == 0) sum--; else if(nums[i] == 1) sum++; if(sum == 0){ ret = i+1; }else{ if(m.count(sum)){ ret = max(ret, i - m[sum]); }else{ m[sum] = i; } } } return ret; } };