当前位置:网站首页>[algorithm] sword finger offer2 golang interview question 10: subarray with sum K
[algorithm] sword finger offer2 golang interview question 10: subarray with sum K
2022-07-06 12:51:00 【Deng Jiawen jarvan】
[ Algorithm ] The finger of the sword offer2 golang Interview questions 10: And for k Subarray
subject 1:
Ideas 1: violence
Time complexity O(n2)
Code
func subarraySum(nums []int, k int) int {
//start: 13:51, 13:57
// Ideas 1: violence , Because there may be negative numbers in elements
// Fix a number i, Record the possibility behind
// Parameter checking
if len(nums) == 0 {
return 0
}
// violence
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
}
test 1
Ideas 2: The prefix and + hashmap
Because there are negative numbers , Therefore, sliding windows cannot be used
Code
func subarraySum(nums []int, k int) int {
//start: 13:51, 13:57
// Ideas 2: The prefix and + hashmap
//
// Parameter checking
if len(nums) == 0 {
return 0
}
// Prefix and + hashmap
sumToCount := make(map[int]int)
sum,resCount := 0,0
sumToCount[0] = 1
for i := 0; i < len(nums); i ++{
sum += nums[i]
// There is sum - sumOld = k, Add to result
resCount += sumToCount[sum - k]
sumToCount[sum] += 1
}
return resCount
}
test
边栏推荐
- Fairygui character status Popup
- Containers and Devops: container based Devops delivery pipeline
- 微信小程序开发心得
- 编译原理:源程序的预处理及词法分析程序的设计与实现(含代码)
- 【rtklib】在rtk下使用抗差自适应卡尔曼滤波初步实践
- Mysql database reports an error: row size too large (> 8126) Changing some columns to TEXT or BLOB or using ROW_ FORMAT=DY
- Prove the time complexity of heap sorting
- FGUI工程打包发布&导入Unity&将UI显示出来的方式
- Office提示您的许可证不是正版弹框解决
- [leetcode15] sum of three numbers
猜你喜欢
随机推荐
Programming homework: educational administration management system (C language)
[Chongqing Guangdong education] Shandong University College Physics reference materials
(the first set of course design) sub task 1-5 317 (100 points) (dijkstra: heavy edge self loop)
(4) Data visualization of R language -- matrix chart, histogram, pie chart, scatter chart, linear regression and strip chart
Teach you to release a DeNO module hand in hand
[Yu Yue education] guide business reference materials of Wuxi Vocational and Technical College of Commerce
Fairygui character status Popup
Vulnhub target: hacknos_ PLAYER V1.1
FairyGUI简单背包的制作
Design and implementation of general interface open platform - (39) simple and crude implementation of API services
FairyGUI簡單背包的制作
In 2020, the average salary of IT industry exceeded 170000, ranking first
NovAtel 板卡OEM617D配置步骤记录
FairyGUI按钮动效的混用
【干货】提升RTK模糊度固定率的建议之周跳探测
[算法] 剑指offer2 golang 面试题7:数组中和为0的3个数字
Combination of fairygui check box and progress bar
Latex learning
3月15号 Go 1.18 正式版发布 了解最新特色以及使用方法
Unity3D摄像机,键盘控制前后左右上下移动,鼠标控制旋转、放缩