Leetcode_C++之525. Contiguous Array(连续子数组)
创始人
2024-02-29 09:38:12
0

题目名称

Contiguous Array

题目描述

Given a binary array nums, return the maximum length of a contiguous subarray with an equal number of 0 and 1.

Example 1:
Input: nums = [0,1]
Output: 2
Explanation: [0, 1] is the longest contiguous subarray with an equal number of 0 and 1.

Example 2:
Input: nums = [0,1,0]
Output: 2
Explanation: [0, 1] (or [1, 0]) is a longest contiguous subarray with equal number of 0 and 1.

Constraints:
1 <= nums.length <= 10e5
nums[i] is either 0 or 1.

初试思路

见注释和视频b站

初试代码

// 我的代码
class Solution {
public:int findMaxLength(vector& nums) {// 遍历从下标i到下标j的子串中符合条件的最长的子串,返回其长度// 即count0[i to j] == count1[i to j] // => count0[0 to j] - count0[0 to i] == count1[0 to j] - count1[0 to i]// => count0[0 to j] - count1[0 to j] == count0[0 to i] - count1[0 to i]// => diffcount[j] == diffcount[i]// 遍历找到符合条件的最大的 i to j的长度int MaxLen = 0; //最大子串长度int MaxJ = 0;   //最大的j的值// diffcount数组存放nums中从下标0到每个下标的“0的个数与1的个数差”,其长度为nums.size()+1,原因见初始化vector diffcount(nums.size()+1); // -1 0 1 2 ... nums.size()-1diffcount[dindex(-1)] = 0; //下标0之前的下标“-1”对应的元素置零0// 初始化diffcount数组, 如果nums[i]==0,则将diffcount[dindex(i)]的值置为前一个元素+1//                      如果nums[i]==1,则将diffcount[dindex(i)]的值置为前一个元素-1for(int i=0; i maxj(nums.size()*2+1); // -nums.size ... 0 ... nums.size()for(int i=-nums.size(); i MaxLen) //if(MaxJ-i+1 > MaxLen) //会使得Maxlen = 1而这明显是错的MaxLen = MaxJ-i+1;    }return MaxLen;   }int dindex(int i){return i+1;}int mindex(int i, int size){return i+size;}};

推荐思路

1、一个数组即可,存放当前0的个数和1的个数的差
2、因为数组是稀疏的,好多用不到,所以可以用哈希表

推荐代码

// 别人的代码1
class Solution {
public:int findMaxLength(vector& nums) {vector arr(2*nums.size() + 1, INT_MIN);arr[nums.size()] = -1;int maxLen = 0, sum = 0;for (int i = 0; i < nums.size(); i++) {sum += (nums[i] == 0 ? -1 : 1);if (arr[sum + nums.size()] >= -1)  maxLen = max(maxLen, i - arr[sum + nums.size()]);else  arr[sum + nums.size()] = i; }return maxLen;}
};
//别人的代码2
class Solution {
public:int findMaxLength(vector& nums) {int sum=0, maxLen=0;unordered_map seen{{0, -1}};for(int i=0; i

相关内容

热门资讯

AWSECS:访问外部网络时出... 如果您在AWS ECS中部署了应用程序,并且该应用程序需要访问外部网络,但是无法正常访问,可能是因为...
AWSElasticBeans... 在Dockerfile中手动配置nginx反向代理。例如,在Dockerfile中添加以下代码:FR...
银河麒麟V10SP1高级服务器... 银河麒麟高级服务器操作系统简介: 银河麒麟高级服务器操作系统V10是针对企业级关键业务...
北信源内网安全管理卸载 北信源内网安全管理是一款网络安全管理软件,主要用于保护内网安全。在日常使用过程中,卸载该软件是一种常...
AWR报告解读 WORKLOAD REPOSITORY PDB report (PDB snapshots) AW...
AWS管理控制台菜单和权限 要在AWS管理控制台中创建菜单和权限,您可以使用AWS Identity and Access Ma...
​ToDesk 远程工具安装及... 目录 前言 ToDesk 优势 ToDesk 下载安装 ToDesk 功能展示 文件传输 设备链接 ...
群晖外网访问终极解决方法:IP... 写在前面的话 受够了群晖的quickconnet的小水管了,急需一个新的解决方法&#x...
不能访问光猫的的管理页面 光猫是现代家庭宽带网络的重要组成部分,它可以提供高速稳定的网络连接。但是,有时候我们会遇到不能访问光...
Azure构建流程(Power... 这可能是由于配置错误导致的问题。请检查构建流程任务中的“发布构建制品”步骤,确保正确配置了“Arti...