【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 ...
随机推荐
- javaSE中级篇3——集合体系(另外一种存储容器)——更新完毕
集合还是一种工具,所以它们的包都在java.util包下 1.集合的整个体系结构(是需要掌握的体系,完全体系不是这样) 对图中所说的 序和重复 这两词的说明: 序:指的是添加进去的元素和取出来的元素 ...
- day18定时任务
day18定时任务 什么是定时任务 类似日常生活之中的闹钟:主要用于定时执行某些命令,达到定时处理数据的作用. 作用: 1.类似生活中使用的闹钟 2.可以自动完成操作命令 3.定时备份系统数据信息 定 ...
- Scala和Java的List集合互相转换
import java.util import scala.collection.mutable /** * 集合互相转换 */ object ScalaToJava { def main(args: ...
- Angular @Input讲解及用法
1.什么是@input @input的作用是定义模块输入,是用来让父级组件向子组件传递内容. 2.@input用法 首先在子组件中将需要传递给父组件的变量用@input()修饰 需要在子组件ts文件i ...
- Vue面试专题(未完)
1.谈一下你对MVVM原理的理解 传统的 MVC 指的是,用户操作会请求服务端路由,路由会调用对应的控制器来处理,控制器会获取数 据.将结果返回给前端,页面重新渲染. MVVM :传统的前端会将数 ...
- FileReader (三) - 网页拖拽并预显示图片简单实现
以下是一个很贱很简单的一个 在网页上图拽图片并预显示的demo. 我是从https://developer.mozilla.org/en-US/docs/Web/API/FileReader#Stat ...
- C++类的定义,成员函数的定义,对象的创建与使用
类是一个模板,可用类生成一系列可用的实例.例如 int B就是生成了一个符合int的数据B,类也是一样,使用类名就可以直接生成一个实例, 该实例中包含类中所有的数据类型和对这些数据的操作方法. 首先, ...
- 面试 Java 后端开发的感受
上周,密集面试了若干位Java后端候选人,工作经验在3到5年间.我的标准其实不复杂(适用90%小小小公司,BAT等自动忽略): 第一能干活,第二Java基础要好,第三最好熟悉些分布式框架.我相信其它公 ...
- javaAPI1
Iterable<T>接口, Iterator<T> iterator() Collection<E>:接口,add(E e) ,size() , Object[] ...
- SpringBoot让测试类飞起来的方法
单元测试是项目开发中必不可少的一环,在 SpringBoot 的项目中,我们用 @SpringBootTest 注解来标注一个测试类,在测试类中注入这个接口的实现类之后对每个方法进行单独测试. 比如下 ...