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.

Approach #1: C++.

class Solution {
public:
int findMaxLength(vector<int>& nums) {
int ans = 0;
int size = nums.size();
unordered_map<int, int> prefix_sum; // store the first position where the sum first appeared.
int sum = 0;
for (int i = 0; i < size; ++i) {
sum += nums[i] ? 1 : -1;
if (sum == 0) ans = i+1;
else if (!prefix_sum.count(sum)) prefix_sum[sum] = i;
else ans = max(ans, i - prefix_sum[sum]);
} return ans;
}
};

  

Approach #2: Java.

class Solution {
public int findMaxLength(int[] nums) {
for (int i = 0; i < nums.length; ++i) {
if (nums[i] == 0) nums[i] = -1;
} Map<Integer, Integer> sumToIndex = new HashMap<>();
sumToIndex.put(0, -1);
int sum = 0, max = 0; for (int i = 0; i < nums.length; ++i) {
sum += nums[i];
if (sumToIndex.containsKey(sum)) {
max = Math.max(max, i - sumToIndex.get(sum));
} else {
sumToIndex.put(sum, i);
}
}
return max;
}
}

  

Approach #3: Python.

class Solution(object):
def findMaxLength(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
count = 0
max_length = 0
table = {0 : 0}
for index, num in enumerate(nums, 1):
if num == 0:
count -= 1
else:
count += 1 if count in table:
max_length = max(max_length, index - table[count])
else:
table[count] = index return max_length

  

Analysis:

In this problem if we use double cycle traversing the vector to find the subarray, because the length of the given binary array will not exceed 50,000, it will Time Limt Exceeded.

So we can use a hash table to save time using space.

First, we have to make the elements in the nums which equal to 0 transform to -1.

Then we travel the array and calculate the prefix sum. if the sum don't count in hash map, we put sum into the hash table, else i - prefix_sum[sum] is a dummy answer which we want to find.

Having one thing we have to notice is which if the array is [0, 1], you may finding that the prefix sum never appeared in this case, so it will return 0 finally. but the really answer is 2. How can we solve this problem?

  • In approach one we using a if statemen to judge if the answer equal to 0 we coulde make ans = i + 1 using this way we can solve the problem of initialization.
  • In approach two we push the key and value {0, -1} in the first, this have the same effect with the first one.
 

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 相连的数组

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

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

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

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

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

  5. 525 Contiguous Array 连续数组

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

  6. 【leetcode】525. Contiguous Array

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

  7. Contiguous Array with Equal Number of 0 & 1

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

  8. [LeetCode] Contiguous Array 邻近数组

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

  9. [Swift]LeetCode525. 连续数组 | Contiguous Array

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

随机推荐

  1. git和github菜鸟使用步骤

    刚刚在windows7下安装完git.奉上安装步骤. git安装 安装git程序.运行以下操作: 1. $ cd ~/.ssh    //检查计算机ssh密钥 2.假设没有提示:No such fil ...

  2. 初识kbmmw 中的smartbind功能

    关于kbmmw smartbind 的开发原因及思路,大家可以参见官方的博客说明和红鱼儿的翻译. 今天我就实例操作一下,给大家演示一下具体实现. 我们新建一个工程 放几个基本的控件 在单元里面加上引用 ...

  3. Möbius strip

    en.wikipedia.org/wiki/Möbius_strip http://mechproto.olin.edu/final_projects/average_jo.html Fabricat ...

  4. Windows消息、绘图与多线程

    有一个项目,一旦点下按钮后,用死循环不停的读数据,读出后立刻用可视化的方法显示.如果不采用多线程的方法,程序运行都正确,但无法关闭窗口,不清楚是窗口无法通过关闭按钮来接受Windows消息,还是接受了 ...

  5. SAP bseg 使用注意点:1.不要使用;2.有主键再用,

    粗表-簇表 cluster-table BSEGRFBLG 池表 pool-table 我記的沒錯的話,在21天學會ABAP中有一節是專門在講Cluster table,另外在 www.sapfans ...

  6. SpringBoot-(1)-IDEA创建SpringBoot项目并运行访问接口

    一,安装IDEA mac安装IDEA IDEA配置Tomcat 二,创建SpringBoot项目 1,打开IDEA,点击Create New Project 2,选择自己所安装的JDK.如果没有配置J ...

  7. 【C++基础学习】成员对象与对象数组

    第一部分 对象成员与对象数组 从一个简单的例子开始说起,首先定义一个Coordinate的类,里面有两个公有的成员变量m_iX和m_iY,分别代表横坐标和纵坐标. 接下来,定义一个对象数组cood和一 ...

  8. Oracle Meger into 函数

    Oracle 在 9i 引入了 merge 命令, 通过这个 merge 能够在一个SQL 语句中对一个表同时执行 inserts 和 updates 操作.Merge into 可以实现用 B 表来 ...

  9. Linux升级安装GCC G++ 6.2

    使用yum安装是不可能了,各大仓库也没有,只能自己编译安装了. 系统为CentOS 6.5,gcc为4.4.7 1 下载源代码包 当前最新版为6.2: wget http://ftp.gnu.org/ ...

  10. 在dw中 <!----> 和 /**/ 的区别?

    <!-- -->是HTML的注释标签,使用<和>是符合HTML标签语法规则的./* */是CSS和JS的注释标签.两种注释有各自的使用环境,并且不能相互替代.