当前位置:网站首页>[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

边栏推荐
- Unity scene jump and exit
- [899] ordered queue
- [算法] 剑指offer2 golang 面试题12:左右两边子数组的和相等
- GPS高程拟合抗差中误差的求取代码实现
- Database table splitting strategy
- Fabrication d'un sac à dos simple fairygui
- The service robots that have been hyped by capital and the Winter Olympics are not just a flash in the pan
- 抗差估计在rtklib的pntpos函数(标准单点定位spp)中的c代码实现
- Guided package method in idea
- 编译原理:源程序的预处理及词法分析程序的设计与实现(含代码)
猜你喜欢
随机推荐
[offer78]合并多个有序链表
Unity3D制作注册登录界面,并实现场景跳转
JUC forkjoin and completable future
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
Excel导入,导出功能实现
VLSM variable length subnet mask partition tips
[Clickhouse kernel principle graphic explanation] about the collaborative work of partitioning, indexing, marking and compressed data
【rtklib】在rtk下使用抗差自适应卡尔曼滤波初步实践
It has been solved by personal practice: MySQL row size too large (> 8126) Changing some columns to TEXT or BLOB or using ROW_ FORMAT
Esp8266 connect onenet (old mqtt mode)
[leetcode19] delete the penultimate node in the linked list
Database course design: college educational administration management system (including code)
(课设第一套)1-4 消息传递接口 (100 分)(模拟:线程)
Database table splitting strategy
[offer9]用两个栈实现队列
[算法] 劍指offer2 golang 面試題2:二進制加法
使用rtknavi进行RT-PPP测试
Special palindromes of daily practice of Blue Bridge Cup
Solution to the problem of automatic login in Yanshan University Campus Network
idea中好用的快捷键









