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

Example 1:

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

Example 2:

  1. Input: [0,1,0]
  2. Output: 2
  3. 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 的映射,而不是去更新这个满足题意的子数组的长度,所以要这么初始化,参见代码如下:

解法一:

  1. class Solution {
  2. public:
  3. int findMaxLength(vector<int>& nums) {
  4. int res = , n = nums.size(), sum = ;
  5. unordered_map<int, int> m{{, -}};
  6. for (int i = ; i < n; ++i) {
  7. sum += (nums[i] == ) ? : -;
  8. if (m.count(sum)) {
  9. res = max(res, i - m[sum]);
  10. } else {
  11. m[sum] = i;
  12. }
  13. }
  14. return res;
  15. }
  16. };

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

解法二:

  1. class Solution {
  2. public:
  3. int findMaxLength(vector<int>& nums) {
  4. int res = , n = nums.size(), sum = ;
  5. unordered_map<int, int> m{{, -}};
  6. for (int i = ; i < n; ++i) {
  7. sum += (nums[i] << ) -;
  8. if (m.count(sum)) {
  9. res = max(res, i - m[sum]);
  10. } else {
  11. m[sum] = i;
  12. }
  13. }
  14. return res;
  15. }
  16. };

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. python-4-格式化输出

    前言 有些小伙伴在打印中乱码或者编码不对,在这里讲格式化输出前,先讲下编码.我们都知道目前主流使用就是utf-8编码. 一.编码简介 编码用来让计算机识别,当然我们都知道计算机只能识别01010101 ...

  2. 大咖云集!Kubernetes and Cloud Native Meetup 深圳站开始报名!

    由阿里技术生态联合 CNCF 官方共同出品的 Kubernetes & Cloud Native Meetup 将在 8 月 31 日来到深圳.届时,阿里云.蚂蚁金服高级技术专家将携手来自国内 ...

  3. Linux SELinux 使用操作

    Linux SELinux 使用操作 # 修改 SELinux 启动模式.临时生效 命令:setenforce [0|1] 0:转成 permissive 宽容模式: 1:转成 Enforcing 强 ...

  4. 【05】Nginx:TCP / 正向 / 反向代理 / 负载均衡

    写在前面的话 在我们日常的工作中,不可能所有的服务都是简单的 HTML 静态网页,nginx 作为轻量级的 WEB 服务器,其实我们将它用于更多的地方还是作为我们网站的入口.不管你是后端接口,还是前端 ...

  5. 2019-9-18-WPF-如何调试-binding

    原文:2019-9-18-WPF-如何调试-binding title author date CreateTime categories WPF 如何调试 binding lindexi 2019- ...

  6. Fiddler使用简单

     一,fiddler简介 1.1,什么是fiddler Fiddler是一个http协议调试代理工具,它能够记录并检查所有你的电脑和互联网之间的http通讯,设置断点,查看所有的“进出”Fiddler ...

  7. E203译码模块(3)

    下面的代码译码出指令的立即数,不同的指令有不同的立即数编码形式. //I类型指令的imm,[31:20],符号位扩展成32位. wire [31:0] rv32_i_imm = { {20{rv32_ ...

  8. Kail Linux xface 2019.2

    概述: -OS: Kali-Rolling (2019.2) -DE: XFCE -WM: Arc-Dark -WM Theme: Arc-Dark -Icons: Korla -Term Font: ...

  9. iOS开发之--为UITextField监听数值变化的三种方法

    项目中有个验证码输入直接验证跳转页面,用的RAC来监听textfield的输入值,如下: @weakify(self); [self.codeView.textField.rac_textSignal ...

  10. input子系统四 input事件处理【转】

    转自:https://blog.csdn.net/qwaszx523/article/details/54139897 转自http://blog.csdn.net/coldsnow33/articl ...