当前位置:网站首页>[算法] 剑指offer2 golang 面试题10:和为k的子数组
[算法] 剑指offer2 golang 面试题10:和为k的子数组
2022-07-06 09:18:00 【邓嘉文Jarvan】
[算法] 剑指offer2 golang 面试题10:和为k的子数组
题目1:
思路1: 暴力
时间复杂度 O(n2)
代码
func subarraySum(nums []int, k int) int {
//start: 13:51, 13:57
//思路1: 暴力,因为元素中有可能是负数
//固定一个数字i,记录后面存在的可能性
//参数校验
if len(nums) == 0 {
return 0
}
//暴力
count := 0
for i := 0; i < len(nums); i++{
sum := 0
for j := i; j < len(nums); j++{
sum += nums[j]
if sum == k {
count ++
}
}
}
return count
}
测试1

思路2: 前缀和 + hashmap
因为有负数存在, 所以滑动窗口是不能用的
代码
func subarraySum(nums []int, k int) int {
//start: 13:51, 13:57
//思路2: 前缀和 + hashmap
//
//参数校验
if len(nums) == 0 {
return 0
}
//前缀和和+ hashmap
sumToCount := make(map[int]int)
sum,resCount := 0,0
sumToCount[0] = 1
for i := 0; i < len(nums); i ++{
sum += nums[i]
//存在 sum - sumOld = k,累加到结果中
resCount += sumToCount[sum - k]
sumToCount[sum] += 1
}
return resCount
}
测试

边栏推荐
- Meanings and differences of PV, UV, IP, VV, CV
- 单片机蓝牙无线烧录
- [899]有序队列
- [offer78] merge multiple ordered linked lists
- HCIP Day 12
- NRF24L01 troubleshooting
- Comparative analysis of the execution efficiency of MySQL 5.7 statistical table records
- [Yu Yue education] guide business reference materials of Wuxi Vocational and Technical College of Commerce
- FairyGUI摇杆
- About using @controller in gateway
猜你喜欢
随机推荐
Unity3d camera, the keyboard controls the front and rear left and right up and down movement, and the mouse controls the rotation, zoom in and out
(the first set of course design) 1-4 message passing interface (100 points) (simulation: thread)
Mysql database reports an error: row size too large (> 8126) Changing some columns to TEXT or BLOB or using ROW_ FORMAT=DY
Unity3d makes the registration login interface and realizes the scene jump
Esp8266 connect onenet (old mqtt mode)
MySQL replacement field part content
Servlet
1041 Be Unique (20 point(s))(哈希:找第一个出现一次的数)
rtklib单点定位spp使用抗差估计遇到的问题及解决
FairyGUI增益BUFF数值改变的显示
Pytorch: tensor operation (I) contiguous
idea问题记录
NRF24L01 troubleshooting
Halcon knowledge: gray_ Tophat transform and bottom cap transform
程序设计大作业:教务管理系统(C语言)
Comparative analysis of the execution efficiency of MySQL 5.7 statistical table records
Lock wait timeout exceeded try restarting transaction
NRF24L01故障排查
(课设第一套)1-4 消息传递接口 (100 分)(模拟:线程)
VLSM variable length subnet mask partition tips









