当前位置:网站首页>【无标题】
【无标题】
2022-07-06 09:18:00 【邓嘉文Jarvan】
[算法] 剑指offer2 golang 0和1个数相同的子数组
题目1:
思路1: 暴力
//思路1: 暴力
//将0当作-1看待,
//固定一个,计算后面的位数是否总和位0,计算最大的个数,
//O(n3),优化下计算时间复杂度O(n2)
代码1
func findMaxLength(nums []int) int {
//返回最长的子数组的长度
//start :19.11
//思路1: 暴力
//将0当作-1看待,
//固定一个,计算后面的位数是否总和位0,计算最大的个数,
//O(n3),优化下计算时间复杂度O(n2)
//参数处理
if len(nums) == 0 {
return 0
}
//暴力
max := 0
for i := 0; i < len(nums) - 1; i++ {
//左指针
sum := 1
if nums[i] == 0 {
sum = -1
}
for j := i+1; j < len(nums); j++{
if nums[j] == 0 {
sum--
}else {
sum++
}
// 符合条件刷新最大值 max
temp := j - i +1
if sum == 0 && temp > max{
max = temp
}
}
}
return max
}
测试1
思路2: hashmap
//1.使用 hashmap[sum]index 记录前 n 个元素和位 sum 的下标,如果后面的元素 sum2
//如果 sum2 - sum1 = 0, sum2 = sum1,证明存在就取之前的 value
代码2:
func findMaxLength(nums []int) int {
//返回最长的子数组的长度
//start :19.26
//思路2: hashmap
//1.使用 hashmap[sum]index 记录前 n 个元素和位 sum 的下标,如果后面的元素 sum2
//如果 sum2 - sum1 = 0, sum2 = sum1,证明存在就取之前的 value
if len(nums) == 0 {
return 0
}
//1.hashmap 赋值
hashmap := make(map[int]int)
//处理边界
hashmap[0] = -1
sum1,max := 0,0
for i := 0; i < len(nums); i++ {
if nums[i] == 0 {
sum1 --
}else {
sum1 ++
}
if val,ok := hashmap[sum1]; ok {
length := i - val
if length > max {
max = length
}
}else {
//只是保留小index的,大的不需要
hashmap[sum1] = i
}
}
return max
}
边栏推荐
- 2021.11.10汇编考试
- FairyGUI循环列表
- (一)R语言入门指南——数据分析的第一步
- Teach you to release a DeNO module hand in hand
- Unity3D,阿里云服务器,平台配置
- Unity3d makes the registration login interface and realizes the scene jump
- [offer29] sorted circular linked list
- SSD technical features
- [offer78] merge multiple ordered linked lists
- Unity scene jump and exit
猜你喜欢
FairyGUI简单背包的制作
Affichage du changement de valeur du Buff de gain de l'interface graphique de défaillance
FairyGUI摇杆
程序设计大作业:教务管理系统(C语言)
单片机蓝牙无线烧录
Naive Bayesian theory derivation
Unity3D,阿里云服务器,平台配置
Matlab读取GNSS 观测值o文件代码示例
Database course design: college educational administration management system (including code)
Particle system for introduction to unity3d Foundation (attribute introduction + case production of flame particle system)
随机推荐
Unity3D制作注册登录界面,并实现场景跳转
What are the functions and features of helm or terrain
基本Dos命令
FairyGUI增益BUFF数值改变的显示
ORA-02030: can only select from fixed tables/views
JUC forkjoin and completable future
Compile GDAL source code with nmake (win10, vs2022)
NRF24L01故障排查
FairyGUI简单背包的制作
[Leetcode15]三数之和
[Offer18]删除链表的节点
Matlab读取GNSS 观测值o文件代码示例
Theoretical derivation of support vector machine
(core focus of software engineering review) Chapter V detailed design exercises
Unity3D摄像机,键盘控制前后左右上下移动,鼠标控制旋转、放缩
Unity scene jump and exit
Office提示您的许可证不是正版弹框解决
The master of double non planning left the real estate company and became a programmer with an annual salary of 25W. There are too many life choices at the age of 25
Fabrication d'un sac à dos simple fairygui
Flink late data processing (3)