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] Contiguous Array 邻近数组的更多相关文章

  1. 994.Contiguous Array 邻近数组

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

  2. [LeetCode] Patching Array 补丁数组

    Given a sorted positive integer array nums and an integer n, add/patch elements to the array such th ...

  3. [LeetCode] Rotate Array 旋转数组

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

  4. [LeetCode] 565. Array Nesting 数组嵌套

    A zero-indexed array A of length N contains all integers from 0 to N-1. Find and return the longest ...

  5. LeetCode Rotate Array 翻转数组

    题意:给定一个数组,将该数组的后k位移动到前n-k位之前.(本题在编程珠玑中第二章有讲) 思路: 方法一:将后K位用vector容器装起来,再移动前n-k位到后面,再将容器内k位插到前面. class ...

  6. 525 Contiguous Array 连续数组

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

  7. LeetCode 525. Contiguous Array

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

  8. Contiguous Array with Equal Number of 0 & 1

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

  9. C++ STL@ list 应用 (leetcode: Rotate Array)

    STL中的list就是一双向链表,可高效地进行插入删除元素. List 是 C++标准程式库 中的一个 类 ,可以简单视之为双向 连结串行 ,以线性列的方式管理物件集合.list 的特色是在集合的任何 ...

随机推荐

  1. Sweet Butter 香甜的黄油

    Sweet Butter 香甜的黄油 题目大意:m个点,n头奶牛,p条边,每一头奶牛在一个点上,一个点可以有多只奶牛,求这样一个点,使得所有奶牛到这个点的距离之和最小. 注释:n<=500 , ...

  2. shell死循环脚本示例

    1.设计一个脚本,监控远程的一台机器(假设ip为192.168.0.28)的存活状态,当发现宕机时发一封邮件给你自己. 提示:1. 你可以使用ping命令   ping -c10 www.baidu. ...

  3. thinkphp5学习

    1.路由的问题 1.1 // pathinfo分隔符 'pathinfo_depr' => '-'设置-后,如果访问的是/index/index 化,路由规则就不能解析 必须改为index-in ...

  4. geotrellis使用(三十六)瓦片入库更新图层

    前言 Geotrellis 是针对大数据量栅格数据进行分布式空间计算的框架,这一点毋庸置疑,并且无论采取何种操作,其实都是先将大块的数据切割成一定大小的小数据(专业术语为瓦片),这是分治的思想,也是分 ...

  5. 【Spring系列】Spring mvc整合druid

    一.pom.xml中添加druid依赖 <!-- druid --> <dependency> <groupId>com.alibaba</groupId&g ...

  6. mysql数据库导入sql文件时提示“Error Code: 1153 - Got a packet bigger than 'max_allowed_packet' bytes”解决办法

    向mysql数据库中导入sql文件时,如果文件过大(几百M),会提示"Error Code: 1153 - Got a packet bigger than 'max_allowed_pac ...

  7. 20162328蔡文琛week05

    学号 20162328 <程序设计与数据结构>第X周学习总结 教材学习内容总结 面向对象程序设计的核心是类的定义,它代表定义了状态和行为的对象. 变量的作用域依赖于变量声明的位置,作用域决 ...

  8. 用greenlet实现Python中的并发

    from greenlet import greenlet def test1(): print 12 gr2.switch() print 34 def test2(): print 56 gr1. ...

  9. XCode Build Settings中几种Search Paths

    Header search path:去查找头文件的路径,同在在你需要使用第三方库的时候,在这里设置你的头文件路径目录,如图 <code><span class="str& ...

  10. Session的过期时间如何计算?

    在生成session的时候,会设置一个session过期时间.session的过期时间并不是从生成session对象开始计算,超过过期时间,session就失效了. 而是每当一个浏览器请求,sessi ...