1、描述
给定一个二进制数组 nums , 找到含有相同数量的 0 和 1 的最长连续子数组,并返回该子数组的长度。
示例 1:
输入: nums = [0,1]
输出: 2
说明: [0, 1] 是具有相同数量0和1的最长连续子数组。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/contiguous-array
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
2、关键字,
数组,最长,相同,
3、思路
前缀和统计出现的次数,
把0转成-1,一起计算,
使用hash保存次数,
4、notes
以后见到0和1就想着变成+1,和-1吧
5、复杂度
时间:O(N)
空间:O(n)小于等于n
6、code
使用两行n列的数组存起来,然后再两层循环遍历统计,又会时间超限制,
// 0变-1,再使用前缀和,
//使用hash存起来
class Solution {
public:
int findMaxLength(vector<int>& nums) {
int n = nums.size();
int res =0;
if(n<2) return 0;
unordered_map<int,int>mp; // 保存第一次 出现的数字 到下标位置的hash
mp[0] = -1;
int counter = 0; // 是1就加1,是0就减一
for(int i = 0;i < n; i++){
if(nums[i] > 0){ // 如果是 1
counter++;
}else{
counter--;
}
if(mp.count(counter)){ // 之间有没有出现过,如果出现过,就有机会是结果,
res = max(res,i -mp[counter]);
}
else{
mp[counter] = i; // 没出现过,就存进来。
}
}
return res;
}
};
/
//方法二
class Solution {
public:
int findMaxLength(vector<int>& nums) {
int n = nums.size();
if(n<2) return 0;
vector<vector<int>>countmy(2,vector<int>(n,0));
int res = 0;
if(nums[0] == 0){
countmy[0][0] = 1;
countmy[1][0] = 0;
}
else{
countmy[1][0] = 1;
countmy[0][0] = 0;
}
for(int i = 1;i < n; i++){
if(nums[i] == 0){
countmy[0][i] = 1 + countmy[0][i-1];
countmy[1][i] = countmy[1][i-1]; //
}
else{
countmy[1][i] = 1 + countmy[1][i-1];
countmy[0][i] = countmy[0][i-1]; //
}
if(countmy[0][i] == countmy[1][i]){
res = max(res,i+1);
}
}
for(int i = 1;i < n;i++){
for(int j = 0; j < i;j++){
if(countmy[0][i] - countmy[0][j] ==countmy[1][i] - countmy[1][j]){
res = max(res,i - j );
}
}
}
return res;
}
};