当前位置:网站首页>[算法] 剑指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
}
测试

边栏推荐
- 第一人称视角的角色移动
- Unity3D摄像机,键盘控制前后左右上下移动,鼠标控制旋转、放缩
- FGUI工程打包发布&导入Unity&将UI显示出来的方式
- Matlab读取GNSS 观测值o文件代码示例
- Agile development helps me
- It has been solved by personal practice: MySQL row size too large (> 8126) Changing some columns to TEXT or BLOB or using ROW_ FORMAT
- Comparative analysis of the execution efficiency of MySQL 5.7 statistical table records
- Idea problem record
- GNSS定位精度指标计算
- 【RTKLIB 2.4.3 b34 】版本更新简介一
猜你喜欢

The service robots that have been hyped by capital and the Winter Olympics are not just a flash in the pan

MySQL time, time zone, auto fill 0

基本Dos命令

NRF24L01故障排查

JS Title: input array, exchange the largest with the first element, exchange the smallest with the last element, and output array.

ORA-02030: can only select from fixed tables/views

FairyGUI循环列表

编译原理:源程序的预处理及词法分析程序的设计与实现(含代码)

Unity3d makes the registration login interface and realizes the scene jump

Derivation of logistic regression theory
随机推荐
Conditional probability
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
單片機藍牙無線燒錄
ORA-02030: can only select from fixed tables/views
[leetcode19] delete the penultimate node in the linked list
dosbox第一次使用
In 2020, the average salary of IT industry exceeded 170000, ranking first
基于rtklib源码进行片上移植的思路分享
Intermediate use tutorial of postman [environment variables, test scripts, assertions, interface documents, etc.]
Lean product development - Lean Software Development & lean product development
[offer78]合并多个有序链表
[Yu Yue education] guide business reference materials of Wuxi Vocational and Technical College of Commerce
JUC forkjoin and completable future
Common DOS commands
Compilation principle: preprocessing of source program and design and implementation of lexical analysis program (including code)
rtklib单点定位spp使用抗差估计遇到的问题及解决
What are the functions and features of helm or terrain
(the first set of course design) 1-4 message passing interface (100 points) (simulation: thread)
Flink late data processing (3)
C programming exercise