当前位置:网站首页>[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
边栏推荐
- 程序设计大作业:教务管理系统(C语言)
- Unity3D基础入门之粒子系统(属性介绍+火焰粒子系统案例制作)
- Office提示您的许可证不是正版弹框解决
- [Nodejs] 20. Koa2 onion ring model ----- code demonstration
- How to reduce the shutdown time of InnoDB database?
- [Chongqing Guangdong education] Shandong University College Physics reference materials
- (课设第一套)1-4 消息传递接口 (100 分)(模拟:线程)
- [算法] 剑指offer2 golang 面试题7:数组中和为0的3个数字
- [算法] 剑指offer2 golang 面试题12:左右两边子数组的和相等
- Comparative analysis of the execution efficiency of MySQL 5.7 statistical table records
猜你喜欢
随机推荐
[算法] 剑指offer2 golang 面试题6:排序数组中的两个数字之和
[算法] 剑指offer2 golang 面试题12:左右两边子数组的和相等
【干货】提升RTK模糊度固定率的建议之周跳探测
Fairygui character status Popup
Mysql database index
[算法] 剑指offer2 golang 面试题2:二进制加法
The service robots that have been hyped by capital and the Winter Olympics are not just a flash in the pan
FairyGUI复选框与进度条的组合使用
idea中导包方法
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
Acwing-116 pilot brother
Devops' future: six trends in 2022 and beyond
[算法] 剑指offer2 golang 面试题10:和为k的子数组
isEmpty 和 isBlank 的用法区别
FairyGUI循环列表
编译原理:源程序的预处理及词法分析程序的设计与实现(含代码)
Itext 7 生成PDF总结
It has been solved by personal practice: MySQL row size too large (> 8126) Changing some columns to TEXT or BLOB or using ROW_ FORMAT
Matlab读取GNSS 观测值o文件代码示例
Unity场景跳转及退出