当前位置:网站首页>[算法] 剑指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
}
测试
边栏推荐
- Office prompts that your license is not genuine pop-up box solution
- FairyGUI增益BUFF数值改变的显示
- Prove the time complexity of heap sorting
- 程序设计大作业:教务管理系统(C语言)
- 音乐播放(Toggle && PlayerPrefs)
- 使用rtknavi进行RT-PPP测试
- Design and implementation of general interface open platform - (39) simple and crude implementation of API services
- Problèmes avec MySQL time, fuseau horaire, remplissage automatique 0
- What is the maximum length of MySQL varchar field
- Derivation of logistic regression theory
猜你喜欢
idea中好用的快捷键
数据库课程设计:高校教务管理系统(含代码)
FairyGUI条子家族(滚动条,滑动条,进度条)
Theoretical derivation of support vector machine
[Nodejs] 20. Koa2 onion ring model ----- code demonstration
Mysql database reports an error: row size too large (> 8126) Changing some columns to TEXT or BLOB or using ROW_ FORMAT=DY
Esp8266 connect onenet (old mqtt mode)
2021.11.10 compilation examination
FairyGUI增益BUFF數值改變的顯示
There is no red exclamation mark after SVN update
随机推荐
Vulnhub target: hacknos_ PLAYER V1.1
音乐播放(Toggle && PlayerPrefs)
FairyGUI增益BUFF数值改变的显示
idea中导包方法
FairyGUI增益BUFF數值改變的顯示
[leetcode19] delete the penultimate node in the linked list
[offer29] sorted circular linked list
[offer18] delete the node of the linked list
Flink late data processing (3)
Common DOS commands
Unity3D,阿里云服务器,平台配置
Fairygui character status Popup
[899] ordered queue
Meanings and differences of PV, UV, IP, VV, CV
Theoretical derivation of support vector machine
Unity3D制作注册登录界面,并实现场景跳转
Special palindromes of daily practice of Blue Bridge Cup
燕山大学校园网自动登录问题解决方案
[Leetcode15]三数之和
(3) Introduction to bioinformatics of R language - function, data Frame, simple DNA reading and analysis