当前位置:网站首页>[算法] 剑指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
}
测试
边栏推荐
- Knowledge system of digital IT practitioners | software development methods -- agile
- [offer29] sorted circular linked list
- 抗差估计在rtklib的pntpos函数(标准单点定位spp)中的c代码实现
- 【干货】提升RTK模糊度固定率的建议之周跳探测
- Unity3d, Alibaba cloud server, platform configuration
- What are the advantages of using SQL in Excel VBA
- Matlab读取GNSS 观测值o文件代码示例
- (the first set of course design) 1-4 message passing interface (100 points) (simulation: thread)
- C programming exercise
- @The difference between Autowired and @resource
猜你喜欢
NRF24L01 troubleshooting
ESP8266连接onenet(旧版MQTT方式)
Theoretical derivation of support vector machine
Halcon knowledge: gray_ Tophat transform and bottom cap transform
Database course design: college educational administration management system (including code)
ORA-02030: can only select from fixed tables/views
2021.11.10汇编考试
Guided package method in idea
JS function promotion and declaration promotion of VaR variable
FairyGUI简单背包的制作
随机推荐
RTKLIB: demo5 b34f.1 vs b33
(5) Introduction to R language bioinformatics -- ORF and sequence analysis
Knowledge system of digital IT practitioners | software development methods -- agile
FairyGUI复选框与进度条的组合使用
基本Dos命令
Combination of fairygui check box and progress bar
如何给Arduino项目添加音乐播放功能
What are the advantages of using SQL in Excel VBA
(the first set of course design) sub task 1-5 317 (100 points) (dijkstra: heavy edge self loop)
(课设第一套)1-5 317号子任务 (100 分)(Dijkstra:重边自环)
Excel导入,导出功能实现
【GNSS数据处理】赫尔默特(helmert)方差分量估计解析及代码实现
idea中好用的快捷键
Idea problem record
Containers and Devops: container based Devops delivery pipeline
Design and implementation of general interface open platform - (39) simple and crude implementation of API services
Programming homework: educational administration management system (C language)
微信小程序开发心得
【RTKLIB 2.4.3 b34 】版本更新简介一
單片機藍牙無線燒錄