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. Debug 路漫漫-14:Python: AttributeError: module 'tensorflow' has no attribute 'sub'

    在调试 <Neural Factorization Machines for Sparse Predictive Analytics>论文的源码(https://github.com/he ...

  2. php explode容易犯的错误

    php explode容易犯的错误 <pre> $pos = strpos($v, 'Controller'); if (is_numeric($pos)) { $kongzhiqifeg ...

  3. Linux 搭建邮件服务器

    一.概述: 在配置邮件服务器之前,先解释几个概念. 1.SMTP:简单邮件传输协议 (Simple Mail Transfer Protocol, SMTP) 通常使用Email都很容易,但是Inte ...

  4. 缘起 Dubbo ,讲讲 Spring XML Schema 扩展机制

    背景 在 Dubbo 中,可以使用 XML 配置相关信息,也可以用来引入服务或者导出服务.配置完成,启动工程,Spring 会读取配置文件,生成注入 相关 Bean.那 Dubbo 如何实现自定义 X ...

  5. WPF 通过Win32SDK修改窗口样式

    使用函数为 SetWindowLong GetWindowLong 注册函数 [DllImport("user32.dll", EntryPoint = "GetWind ...

  6. 转 经典分类网络Googlenet

    转自https://my.oschina.net/u/876354/blog/1637819 2014年,GoogLeNet和VGG是当年ImageNet挑战赛(ILSVRC14)的双雄,GoogLe ...

  7. 2019-11-25-加强版在国内分发-UWP-应用正确方式-通过win32安装UWP应用

    原文:2019-11-25-加强版在国内分发-UWP-应用正确方式-通过win32安装UWP应用 title author date CreateTime categories 加强版在国内分发 UW ...

  8. Visual Studio 2017使用ODT 连接Oracle 数据库出现异常

    2019.5.23 更新 突然发现原来是是sqlnet.ora在搞鬼,只要将SQLNET.AUTHENTICATION_SERVICES=(nts)  改为 SQLNET.AUTHENTICATION ...

  9. Windows Service 服务搭配FluentScheduler实现定时任务调度

    Windows Service 服务 创建Windows Service 项目 创建一个Windows Service项目,并将项目名称改为 TaskWindowService 在解决方案资源管理器内 ...

  10. python time包中的time.time()和time.clock()的区别

    在统计python代码 执行速度时要使用到time包,在查找相关函数时有time.time()和time.clock()两个函数可供选择.而两者是有区别的: cpu 的运行机制:cpu是多任务的,例如 ...