当前位置:网站首页>剑指 Offer II 011. 0 和 1 个数相同的子数组
剑指 Offer II 011. 0 和 1 个数相同的子数组
2022-04-21 16:59:00 【瑾怀轩】
给定一个二进制数组 nums , 找到含有相同数量的 0 和 1 的最长连续子数组,并返回该子数组的长度。
示例 1:
输入: nums = [0,1]
输出: 2
说明: [0, 1] 是具有相同数量 0 和 1 的最长连续子数组。
示例 2:
输入: nums = [0,1,0]
输出: 2
说明: [0, 1] (或 [1, 0]) 是具有相同数量 0 和 1 的最长连续子数组。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/A1NYOS
【python】前缀和+字典
class Solution:
def findMaxLength(self, nums: List[int]) -> int:
#利用前缀和思想+哈希表,定义counter,遇0减1 , 遇1加1.
counter = 0
#定义字典,存放前缀和与当前坐标。设置首置位前缀和为0,当数组两个元素的情形,1- (-1) = 2
preSum = {0:-1}
#定义最大连续子串长度,如果当前前缀和字典中存在时,那么i - preSum【counter】便是当前等0的连续子串
maxLen = 0
for i in range(len(nums)):
#计算前缀和counter
counter += 1 if nums[i] == 1 else -1
#判断字典中是否有当前前缀和, 那么i - preSum【counter】便是当前等0的连续子串
if counter in preSum:
maxLen = max(maxLen,i - preSum.get(counter))
#没有时,存放counter和当前元素下标,当已经存在不用更新下标,现在求最长连续数组,
else:
preSum[counter] = i
return maxLen
版权声明
本文为[瑾怀轩]所创,转载请带上原文链接,感谢
https://blog.csdn.net/ckq707718837/article/details/124321262
边栏推荐
- R语言使用plot函数可视化数据散点图,使用par函数中的bg参数自定义设置可视化图像线框内的背景色
- Rebound shell of program classes with different characteristics
- 搜狗某频道存在SQL注入漏洞
- .NET Core企业微信网页授权登录
- 【一篇文章帮你打好路由基础】
- IO view command
- Database Principle -- library management system
- How to judge whether a binary differential equation is a total differential
- 从源码角度分析创建线程池究竟有哪些方式
- 域内信息查询工具AdFind
猜你喜欢

机器学习吴恩达课程总结(四)

【观察】紫光云:同构混合云升级为分布式云,让云和智能无处不在

. net treasure API: ihostedservice, background task execution

338-Leetcode 同构字符串

338 leetcode isomorphic string

pytorch index_add_用法介绍

Mina中的Scan State

Apache security configuration

mysql:1103 错误解决方案

Microcomputer principle and interface technology -- electronic organ experiment report
随机推荐
The R language uses the plot function to visualize the data scatter diagram. The col parameter is set as factor variable and custom color list. The data points in different groups are displayed in dif
Multi core and multi CPU programming -- task scheduling
Microsoft IE local file detection vulnerability
Summary of Wu Enda's course of machine learning (4)
干货 | 实战演练基于加密接口测试测试用例设计
机器学习吴恩达课程总结(一)
一、数据库系列之数据库系统概述
俄罗斯门户网站 Yandex 开源 YDB 数据库
338-Leetcode 同构字符串
Quick MTF, lens image quality test application
Image Manipulation Detection by Multi-View Multi-Scale Supervision
域内信息查询工具AdFind
2-4. Port binding
sohu白社会跨站漏洞
. net treasure API: ihostedservice, background task execution
1、 Overview of database system of database Series
搜狗某频道存在SQL注入漏洞
MySQL的优势
Mongodb security configuration
不同特征程序类反弹shell