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的个数之间产生联系呢?这里需要用到一个 trick,遇到1就加1,遇到0,就减1,这样如果某个子数组和为0,就说明0和1的个数相等,这个想法真是太叼了,不过博主木有想出来。知道了这一点,就用一个 HashMap 建立子数组之和跟结尾位置的坐标之间的映射。如果某个子数组之和在 HashMap 里存在了,说明当前子数组减去 HashMap 中存的那个子数字,得到的结果是中间一段子数组之和,必然为0,说明0和1的个数相等,更新结果 res。注意这里需要在 HashMap 初始化一个 0 -> -1 的映射,这是为了当 sum 第一次出现0的时候,即这个子数组是从原数组的起始位置开始,需要计算这个子数组的长度,而不是建立当前子数组之和 sum 和其结束位置之间的映射。比如就拿例子1来说,nums = [0, 1],当遍历0的时候,sum = -1,此时建立 -1 -> 0 的映射,当遍历到1的时候,此时 sum = 0 了,若 HashMap 中没有初始化一个 0 -> -1 的映射,此时会建立 0 -> 1 的映射,而不是去更新这个满足题意的子数组的长度,所以要这么初始化,参见代码如下:

解法一:

class Solution {
public:
int findMaxLength(vector<int>& nums) {
int res = , n = nums.size(), sum = ;
unordered_map<int, int> m{{, -}};
for (int i = ; i < n; ++i) {
sum += (nums[i] == ) ? : -;
if (m.count(sum)) {
res = max(res, i - m[sum]);
} else {
m[sum] = i;
}
}
return res;
}
};

下面这种方法跟上面的解法基本上完全一样,只不过在求累积和的时候没有用条件判断,而是用了一个很叼的等式直接包括了两种情况,参见代码如下:

解法二:

class Solution {
public:
int findMaxLength(vector<int>& nums) {
int res = , n = nums.size(), sum = ;
unordered_map<int, int> m{{, -}};
for (int i = ; i < n; ++i) {
sum += (nums[i] << ) -;
if (m.count(sum)) {
res = max(res, i - m[sum]);
} else {
m[sum] = i;
}
}
return res;
}
};

Github 同步地址:

https://github.com/grandyang/leetcode/issues/525

类似题目:

Maximum Size Subarray Sum Equals k

参考资料:

https://leetcode.com/problems/contiguous-array/

https://leetcode.com/problems/contiguous-array/discuss/99646/Easy-Java-O(n)-Solution-PreSum-%2B-HashMap

https://leetcode.com/problems/contiguous-array/discuss/99652/One-passuse-a-HashMap-to-record-0-1-count-difference

LeetCode All in One 题目讲解汇总(持续更新中...)

[LeetCode] 525. Contiguous Array 相连的数组的更多相关文章

  1. LeetCode 525. Contiguous Array

    525. Contiguous Array Add to List Description Submission Solutions Total Accepted: 2476 Total Submis ...

  2. 【LeetCode】525. Contiguous Array 解题报告(Python & C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 累积和 日期 题目地址:https://leetco ...

  3. 525 Contiguous Array 连续数组

    给定一个二进制数组, 找到含有相同数量的 0 和 1 的最长连续子数组.示例 1:输入: [0,1]输出: 2说明: [0, 1] 是具有相同数量0和1的最长连续子数组. 示例 2:输入: [0,1, ...

  4. 【leetcode】525. Contiguous Array

    题目如下: 解题思路:这个题目可以这么做,遍历数组,如果元素是0,则count --:否则count ++:这样的话,每遍历到一个下标i,count的值就是0>i区间内0和1的差值.如果我们能找 ...

  5. LeetCode 189. Rotate Array (旋转数组)

    Rotate an array of n elements to the right by k steps. For example, with n = 7 and k = 3, the array  ...

  6. [LeetCode] 457. Circular Array Loop 环形数组循环

    You are given a circular array nums of positive and negative integers. If a number k at an index is ...

  7. 525. Contiguous Array两位求和为1的对数

    [抄题]: Given a binary array, find the maximum length of a contiguous subarray with equal number of 0 ...

  8. 525. Contiguous Array

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

  9. Contiguous Array with Equal Number of 0 & 1

    2018-07-08 13:24:31 问题描述: 问题求解: 问题规模已经给出是50000量级,显然只能是O(n),至多O(nlogn)的复杂度.本题使用DP和滑动数组都比较棘手,这里给出的方案是p ...

随机推荐

  1. IM开发者的零基础通信技术入门(三):国人通信方式的百年变迁

    [来源申明]本文原文来自:微信公众号“鲜枣课堂”,官方网站:xzclass.com,原题为:<中国通信的百年沉浮>,本文引用时已征得原作者同意.为了更好的内容呈现,即时通讯网在收录时内容有 ...

  2. element-ui的tabs默认选中页签

    Element-UI提供了tabs组件(选项卡.多页签),其中在tabs的属性中提供了一个value/v-model属性来绑定默认选中的页签. 我们通过简单的示例来看一下具体是怎么使用的. <t ...

  3. ansible碎碎念

    1. Using a SSH password instead of a key is not possible because Host Key checking is enabled and ss ...

  4. KVM学习笔记--静态迁移

    .静态迁移过程如下 (1)确定虚拟机关闭状态 (2)准备迁移oeltest02虚拟机,查看该虚拟机配置的磁盘文件 (3)导入虚拟机配置文件 [root@node1~]# virsh dumpxml o ...

  5. opencv 图像旋转

    理论 http://www.cnblogs.com/wangguchangqing/p/4045150.html 翻开任意一本图像处理的书,都会讲到图像的几何变换,这里面包括:仿射变换(affine ...

  6. 使用SolrJ客户端管理SolrCloud(Solr集群)

    1.使用SolrJ客户端管理SolrCloud(Solr集群). package com.taotao.search.service; import java.io.IOException; impo ...

  7. mysql只显示表名和备注

    查看某个数据下的表及其备注: select table_name,table_comment from information_schema.tables where table_schema='db ...

  8. python 手机app数据爬取

    目录 一:爬取主要流程简述 二:抓包工具Charles 1.Charles的使用 2.安装 (1)安装链接 (2)须知 (3)安装后 3.证书配置 (1)证书配置说明 (2)windows系统安装证书 ...

  9. 【maven】搭建maven私服--基于CentOS7.6+docker

    一.docker环境 Docker version 19.03.5, build 633a0ea 二.安装并启动 Maven 私服的工具: Sonatype Nexus 1.搜索 2.下载镜像 doc ...

  10. HTTP Protocol

    HTTP协议 1      HTTP请求状态码 当用户试图通过 HTTP 访问一台正在运行 Internet 信息服务 (IIS) 的服务器上的内容时,IIS 返回一个表示该请求的状态的数字代码.状态 ...