作者: 负雪明烛
id: fuxuemingzhu
个人博客: http://fuxuemingzhu.cn/


题目地址:https://leetcode.com/problems/contiguous-array/description/

题目描述

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的数字一样多。

解题方法

累积和

使用的方法是求和+hashmap的方法,首先从头开始遍历,如果当前值是0就sum-1,否则就sum+1.这样如果得到了一个sum就知道在此之前出现了1的个数和0的个数的差值。因此,当后面该sum再次出现的时候,我们就知道了这个差值再次出现,也就是说,从第一次这个差值出现和第二次这个差值出现之间0和1的个数是一样多的。

因此我们需要一个map来保存0和1的差值。如果这个差值没出现过就给它赋值为它出现的索引。我们要求的就是当同样的差值出现的时候,两者之间的最大值。另外注意,当这个差值再次出现的时候不要更新map。即我们的策略是只保存这个差值出现的第一个位置,只有这样我们才知道最长的连续子数组是多少。

这个题的官方解答里面给出了详细的每一步的变化过程,推荐一看。

也可以在刚开始的时候就把nums中的0替换成-1,这样就可以直接使用total_sum加上当地前数值即可。

需要注意的是字典应该有个初始化值,代表在刚开始的时候没有任何元素的位置是-1,否则后面出现0的时不能和最开始的位置求位置差。

python代码如下:

class Solution:
def findMaxLength(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
print(nums)
total_sum = 0
index_map = dict()
index_map[0] = -1
res = 0
for i, num in enumerate(nums):
if num == 0:
total_sum -= 1
else:
total_sum += 1
if total_sum in index_map:
res = max(res, i - index_map[total_sum])
else:
index_map[total_sum] = i
return res

C++代码如下:

class Solution {
public:
int findMaxLength(vector<int>& nums) {
const int N = nums.size();
unordered_map<int, int> m_;
for (int& num : nums) {
if (num == 0) {
num = -1;
}
}
m_.insert({0, -1});
int sums = 0;
int res = 0;
for (int i = 0; i < N; ++i) {
sums += nums[i];
if (m_.count(sums)) {
res = max(res, i - m_[sums]);
}
m_.insert({sums, i});
}
}
return res;
}
};

参考资料:

https://leetcode.com/problems/contiguous-array/discuss/99646/Easy-Java-O(n)-Solution-PreSum-+-HashMap
https://leetcode.com/articles/contiguous-array/

日期

2018 年 9 月 12 日 ———— 做题还是要有耐心

【LeetCode】525. Contiguous Array 解题报告(Python & C++)的更多相关文章

  1. LeetCode 525. Contiguous Array

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

  2. 【LeetCode】26. Remove Duplicates from Sorted Array 解题报告(Python&C++&Java)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 双指针 日期 [LeetCode] https:// ...

  3. [LeetCode] 525. Contiguous Array 相连的数组

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

  4. LeetCode 896 Monotonic Array 解题报告

    题目要求 An array is monotonic if it is either monotone increasing or monotone decreasing. An array A is ...

  5. 【LeetCode】153. Find Minimum in Rotated Sorted Array 解题报告(Python)

    [LeetCode]153. Find Minimum in Rotated Sorted Array 解题报告(Python) 标签: LeetCode 题目地址:https://leetcode. ...

  6. 【LeetCode】697. Degree of an Array 解题报告

    [LeetCode]697. Degree of an Array 解题报告 标签(空格分隔): LeetCode 题目地址:https://leetcode.com/problems/degree- ...

  7. 【LeetCode】120. Triangle 解题报告(Python)

    [LeetCode]120. Triangle 解题报告(Python) 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 题目地址htt ...

  8. LeetCode 1 Two Sum 解题报告

    LeetCode 1 Two Sum 解题报告 偶然间听见leetcode这个平台,这里面题量也不是很多200多题,打算平时有空在研究生期间就刷完,跟跟多的练习算法的人进行交流思想,一定的ACM算法积 ...

  9. 【LeetCode】Permutations II 解题报告

    [题目] Given a collection of numbers that might contain duplicates, return all possible unique permuta ...

随机推荐

  1. matplotlib 画饼图

    有个瑕疵,某一块儿比例过小时,文字会重叠. 1 def pizza(data,labs,title): 2 import matplotlib 3 import matplotlib.pyplot a ...

  2. Linux—yum安装python-pip

    centos下安装pip时失败: [root@wfm ~]# yum -y install pipLoaded plugins: fastestmirror, refresh-packagekit, ...

  3. oracle中char],varchar,varchar2

    VARCHAR.VARCHAR2.CHAR的区别 1.CHAR的长度是固定的,而VARCHAR2的长度是可以变化的, 比如,存储字符串"abc",对于CHAR (20),表示你存储 ...

  4. Spring 注解开发

    目录 注解开发简介 常用注解 启用注解功能 bean 定义:@Component.@Controller.@Service.@Repository bean 的引用类型属性注入:@Autowired. ...

  5. 论文翻译:2020_Weighted speech distortion losses for neural-network-based real-time speech enhancement

    论文地址:基于神经网络的实时语音增强的加权语音失真损失 论文代码:https://github.com/GuillaumeVW/NSNet 引用:Xia Y, Braun S, Reddy C K A ...

  6. Vue 之keep-alive的使用,实现页面缓存

    什么是keep-alive 有时候我们不希望组件被重新渲染影响使用体验: 或者处于性能考虑,避免多次重复渲染降低性能.而是希望组件可以缓存下来,维持当前的状态.这时候就需要用到keep-alive组件 ...

  7. 利用extern共享全局变量

    方法: 在xxx.h中利用extern关键字声明全局变量 extern int a; 在xxx.cpp中#include<xxx.h> 再定义 int a; 赋不赋初值无所谓,之后该全局变 ...

  8. Redis集群的三种模式

    一.主从模式 通过持久化功能,Redis保证了即使在服务器重启的情况下也不会损失(或少量损失)数据,因为持久化会把内存中数据保存到硬盘上,重启会从硬盘上加载数据. 但是由于数据是存储在一台服务器上的, ...

  9. Dubbo提供者的异步执行

    从前面"对提供者的异步调用"例子可以看出,消费者对提供者实现了异步调用,消费者线程的执行过程不再发生阻塞,但提供者对IO耗时操作仍采用的是同步调用,即IO操作仍会阻塞Dubbo的提 ...

  10. jQuery全局进行方法扩展

    <!DOCTYPE html><html><head> <meta charset="UTF-8"> <title>01 ...