当前位置:网站首页>【无标题】
【无标题】
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
}
边栏推荐
- FairyGUI簡單背包的制作
- Agile development helps me
- Vulnhub target: hacknos_ PLAYER V1.1
- (3) Introduction to bioinformatics of R language - function, data Frame, simple DNA reading and analysis
- JUC forkjoin and completable future
- 第一人称视角的角色移动
- [Offer29] 排序的循环链表
- MySQL error warning: a long semaphore wait
- Game 280 weekly
- Introduction to the daily practice column of the Blue Bridge Cup
猜你喜欢
2021.11.10汇编考试
SVN更新后不出现红色感叹号
Naive Bayesian theory derivation
Problèmes avec MySQL time, fuseau horaire, remplissage automatique 0
Unity3d makes the registration login interface and realizes the scene jump
【干货】提升RTK模糊度固定率的建议之周跳探测
Halcon knowledge: gray_ Tophat transform and bottom cap transform
单片机蓝牙无线烧录
FairyGUI复选框与进度条的组合使用
Mixed use of fairygui button dynamics
随机推荐
(四)R语言的数据可视化——矩阵图、柱状图、饼图、散点图与线性回归、带状图
Office提示您的许可证不是正版弹框解决
[offer78]合并多个有序链表
Unity场景跳转及退出
idea中好用的快捷键
Flink late data processing (3)
Guided package method in idea
音乐播放(Toggle && PlayerPrefs)
FairyGUI人物状态弹窗
[offer78] merge multiple ordered linked lists
抗差估计在rtklib的pntpos函数(标准单点定位spp)中的c代码实现
燕山大学校园网自动登录问题解决方案
【GNSS】抗差估计(稳健估计)原理及程序实现
Halcon knowledge: gray_ Tophat transform and bottom cap transform
[Nodejs] 20. Koa2 onion ring model ----- code demonstration
单片机蓝牙无线烧录
(core focus of software engineering review) Chapter V detailed design exercises
About using @controller in gateway
FairyGUI簡單背包的制作
NRF24L01故障排查