【LeetCode】525. Contiguous Array 解题报告(Python & C++)
作者: 负雪明烛
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++)的更多相关文章
- LeetCode 525. Contiguous Array
525. Contiguous Array Add to List Description Submission Solutions Total Accepted: 2476 Total Submis ...
- 【LeetCode】26. Remove Duplicates from Sorted Array 解题报告(Python&C++&Java)
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 双指针 日期 [LeetCode] https:// ...
- [LeetCode] 525. Contiguous Array 相连的数组
Given a binary array, find the maximum length of a contiguous subarray with equal number of 0 and 1. ...
- LeetCode 896 Monotonic Array 解题报告
题目要求 An array is monotonic if it is either monotone increasing or monotone decreasing. An array A is ...
- 【LeetCode】153. Find Minimum in Rotated Sorted Array 解题报告(Python)
[LeetCode]153. Find Minimum in Rotated Sorted Array 解题报告(Python) 标签: LeetCode 题目地址:https://leetcode. ...
- 【LeetCode】697. Degree of an Array 解题报告
[LeetCode]697. Degree of an Array 解题报告 标签(空格分隔): LeetCode 题目地址:https://leetcode.com/problems/degree- ...
- 【LeetCode】120. Triangle 解题报告(Python)
[LeetCode]120. Triangle 解题报告(Python) 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 题目地址htt ...
- LeetCode 1 Two Sum 解题报告
LeetCode 1 Two Sum 解题报告 偶然间听见leetcode这个平台,这里面题量也不是很多200多题,打算平时有空在研究生期间就刷完,跟跟多的练习算法的人进行交流思想,一定的ACM算法积 ...
- 【LeetCode】Permutations II 解题报告
[题目] Given a collection of numbers that might contain duplicates, return all possible unique permuta ...
随机推荐
- centos 安装reids
1.安装tcl支持 yum install tcl 2.安装redis我们以最新的2.8.9为例 $ wget http://download.redis.io/releases/redis-2.8. ...
- C#筛选项联动,联动筛选
protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { FillDep(); } // FillDG(); ...
- c#跳转
Response.Redirect(EditUrl("MEUID", lblMEUID.Text, "Page2", "PageOneMK" ...
- Hadoop运行jar包报错java.lang.Exception: java.lang.ArrayIndexOutOfBoundsException: 1
错误信息: java.lang.Exception: java.lang.ArrayIndexOutOfBoundsException: 1 at org.apache.hadoop.mapre ...
- HDFS01 概述
HDFS 概述 目录 HDFS 概述 HDFS的产生背景和定义 HDFS产生背景 HDFS定义 优缺点 优点 缺点 组成 NameNode DataNode Secondary NameNode(2n ...
- LeetCode数组中重复的数字
LeetCode 数组中重复的数字 题目描述 在一个长度为 n 的数组 nums 里的所有数字都在 0~n-1 的范围内.数组中某些数字是重复的,但不知道有几个数字重复了,也不知道每个数字重复了几次. ...
- 日常Java 2021/10/28
Java lterator Java lterator(迭代器)不是一个集合,它是一种用于访问集合的方法,可用于迭代 ArrayList和HashSet等集合.lterator是Java迭代器最简单的 ...
- Applescript快速入门及OmniFocus每日md报告开发
本篇主要记录 Applescript 基础语法,以及利用 applescript 生成 omnifocus 每日报告 从 windows 转换到 macos,最近一直在不断折腾,这两天浏览 githu ...
- 15. Linux提取RPM包文件(cpio命令)详解
在讲解如何从 RPM 包中提取文件之前,先来系统学习一下 cpio 命令.cpio 命令用于从归档包中存入和读取文件,换句话说,cpio 命令可以从归档包中提取文件(或目录),也可以将文件(或目录)复 ...
- CSS相关,手画三角形,正方形,扇形
三角形 实现一个三角形 <!DOCTYPE html> <html> <head> <title>三角形</title> <style ...