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. LeetCode 234:回文链表 Palindrome Linked List

    ​ 请判断一个链表是否为回文链表. Given a singly linked list, determine if it is a palindrome. 示例 1: 输入: 1->2 输出: ...

  2. pandas使用大全--数据与处理

    1.首先导入pandas库,一般都会用到numpy库,所以我们先导入备用: import numpy as np import pandas as pd 导入CSV或者xlsx文件: df = pd. ...

  3. Taxi Cab Scheme POJ - 2060 二分图最小路径覆盖

    Running a taxi station is not all that simple. Apart from the obvious demand for a centralised coord ...

  4. CSS 控制文字两端对齐

    <html> <head> <style> td:after { content: ''; } td p{ font-size: 14px; width: 5em; ...

  5. 排障利器之远程调试与监控 --jmx & remote debug

    监控和调试功能是应用必备的属性之一,其手段也是多种多样. 一般地,我们可以通过:线上日志, zabbix, grafana, cat 等待系统做一问题留底,有问题及时报警,从而达到监控效果. 而对于应 ...

  6. linq,sqlmethods,like

    LINQ to SQL will translate .NET methods in this manner: text.StartsWith(...) = LIKE ...% text.Contai ...

  7. 基于直接缓冲区和非直接缓冲区的javaIO文件操作

    基本概念: 1. 非直接缓冲区:  指的是通过jvm来缓存数据的,应用程序要读取本地数据要经历从本地磁盘到物理内存,然后copy到jvm中,然后再通过流的方式读取到应用程序中,写的操作正好与之相反. ...

  8. Winform中设置和获取DevExpress的RadioGroup的选中项的value值

    场景 Winform中实现读取xml配置文件并动态配置ZedGraph的RadioGroup的选项: https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article ...

  9. mac中使用expect脚本,让iTerms保存密码登录ssh

    最近工作中需要使用ssh连接到centos服务器中,以前公司都是直接配的私钥就可以免密登录了.这里还用的密码. 由于,我一直用的是iTerm2,所以在网上搜索了下,找到了一种方案,那就是expect脚 ...

  10. 信息收集利器:ZoomEye

    前言 ZoomEye是一款针对网络空间的搜索引擎,收录了互联网空间中的设备.网站及其使用的服务或组件等信息. ZoomEye 拥有两大探测引擎:Xmap 和 Wmap,分别针对网络空间中的设备及网站, ...