当前位置:网站首页>[算法] 剑指offer2 golang 面试题8:和大于或等于k的最短子数组
[算法] 剑指offer2 golang 面试题8:和大于或等于k的最短子数组
2022-07-06 09:18:00 【邓嘉文Jarvan】
[算法] 剑指offer2 golang 面试题8:和大于或等于k的最短子数组
题目1:
思路1: 滑动窗口
//思路: 滑动窗口
//指针 [left,right] 记录连续子数组的区间,并记录区间和 sum
//if sum < target; right ++ ;sum += nums[right]
//if sum >= target; 更新最小长度 minLen; sum -= nums[left]; left++
代码
func minSubArrayLen(target int, nums []int) int {
//思路: 滑动窗口
//指针 [left,right] 记录连续子数组的区间,并记录区间和 sum
//if sum < target; right ++ ;sum += nums[right]
//if sum >= target; 更新最小长度 minLen; sum -= nums[left]; left++
//参数处理
if len(nums) ==0 || target <= 0{
return -1
}
//滑动窗口
minLen := 0
left,right,sum := 0,0,nums[0]
for left <= right{
if sum < target {
right ++
//这里会有指针溢出 todo
if right == len(nums) {
return minLen
}
sum += nums[right]
}else {
//更新最小长度
tempLen := right - left + 1
if tempLen < minLen || minLen == 0{
minLen = tempLen
}
sum -= nums[left]
left ++
}
}
return minLen
}
测试
边栏推荐
- 微信小程序开发心得
- Programming homework: educational administration management system (C language)
- Fabrication of fairygui simple Backpack
- Lock wait timeout exceeded try restarting transaction
- idea中导包方法
- [Nodejs] 20. Koa2 onion ring model ----- code demonstration
- [Chongqing Guangdong education] reference materials for regional analysis and planning of Pingdingshan University
- SSD technical features
- About using @controller in gateway
- C programming exercise
猜你喜欢
Remember an experience of ECS being blown up by passwords - closing a small black house, changing passwords, and changing ports
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代码实现
微信小程序开发心得
NRF24L01 troubleshooting
Liste des boucles de l'interface graphique de défaillance
Office提示您的许可证不是正版弹框解决
Esp8266 connect onenet (old mqtt mode)
Unity场景跳转及退出
RTKLIB: demo5 b34f.1 vs b33
随机推荐
[Offer18]删除链表的节点
VLSM variable length subnet mask partition tips
ESP8266连接onenet(旧版MQTT方式)
[leetcode622]设计循环队列
Fabrication d'un sac à dos simple fairygui
Idea problem record
Flink late data processing (3)
NRF24L01 troubleshooting
Lean product development - Lean Software Development & lean product development
Derivation of logistic regression theory
如何给Arduino项目添加音乐播放功能
What are the advantages of using SQL in Excel VBA
【GNSS数据处理】赫尔默特(helmert)方差分量估计解析及代码实现
Minio file download problem - inputstream:closed
About using @controller in gateway
[Offer29] 排序的循环链表
Teach you to release a DeNO module hand in hand
[leetcode622] design circular queue
Compile GDAL source code with nmake (win10, vs2022)
Remember an experience of ECS being blown up by passwords - closing a small black house, changing passwords, and changing ports