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.
题目内容:
给出一个只包含0和1的数组,找出里面0和1个数一样的最长子数组的长度。
解题思路:
如果我们有一个只包含0和1的数组,和一个变量count,初始值为0,我们从头开始遍历数组,遇到1的时候,count加1,遇到0的时候,count减1,如果遍历完整个数组之后,count的值为0,那么可以说明数组中含有相同的个数的0和1。但是在这里,我们要找的是子数组,我们并不知道这个子数组的的开头和结尾,但是,如果我们用同样的方法遍历一个数组,假如遍历数组[1, 1, 1, 0, 0],我们可以发现count的变化是0->1->2->3->2->1,其中count第1和第5的值为1,对应原数组[1, 5)之间的子数组是包含了相同个数的0和1的。
所以,我们可以用一个map结构,用count的值作为key,用出现这个值的位置作为val,当然这个位置我们可以只保留最开始和最后一个就可以了,最后遍历一次这个map,找到每个key的val中间隔最大的就是题目要的结果。
代码:
class Solution {
public:
int findMaxLength(vector<int>& nums) {
map<int, vector<int>> count2index;
int count = 0;
int max = 0;
count2index.insert(pair<int, vector<int> > (0, vector<int>({-1})));
for (int i = 0; i < nums.size(); i++) {
count += nums[i] == 0 ? -1 : 1;
if (count2index.find(count) == count2index.end()) {
count2index.insert(pair<int, vector<int> > (count, vector<int>()));
}
count2index[count].push_back(i);
}
map<int, vector<int>>::iterator it = count2index.begin();
while (it != count2index.end()) {
int begin = *((it->second).begin());
int end = *((it->second).end() - 1);
if (end - begin > max) max = end - begin;
it++;
}
return max;
}
};