当前位置:网站首页>[algorithm] sword finger offer2 golang interview question 8: the shortest subarray with a sum greater than or equal to K
[algorithm] sword finger offer2 golang interview question 8: the shortest subarray with a sum greater than or equal to K
2022-07-06 12:51:00 【Deng Jiawen jarvan】
[ Algorithm ] The finger of the sword offer2 golang Interview questions 8: And greater than or equal to k The shortest subarray of
subject 1:
Ideas 1: The sliding window
// Ideas : The sliding window
// The pointer [left,right] Record the interval of continuous subarray , And record the interval and sum
//if sum < target; right ++ ;sum += nums[right]
//if sum >= target; Update minimum length minLen; sum -= nums[left]; left++
Code
func minSubArrayLen(target int, nums []int) int {
// Ideas : The sliding window
// The pointer [left,right] Record the interval of continuous subarray , And record the interval and sum
//if sum < target; right ++ ;sum += nums[right]
//if sum >= target; Update minimum length minLen; sum -= nums[left]; left++
// Processing parameters
if len(nums) ==0 || target <= 0{
return -1
}
// The sliding window
minLen := 0
left,right,sum := 0,0,nums[0]
for left <= right{
if sum < target {
right ++
// There will be pointer overflow here todo
if right == len(nums) {
return minLen
}
sum += nums[right]
}else {
// Update minimum length
tempLen := right - left + 1
if tempLen < minLen || minLen == 0{
minLen = tempLen
}
sum -= nums[left]
left ++
}
}
return minLen
}
test
边栏推荐
猜你喜欢
抗差估计在rtklib的pntpos函数(标准单点定位spp)中的c代码实现
[算法] 劍指offer2 golang 面試題2:二進制加法
FairyGUI按钮动效的混用
Particle system for introduction to unity3d Foundation (attribute introduction + case production of flame particle system)
Unity3d, Alibaba cloud server, platform configuration
There is no red exclamation mark after SVN update
微信小程序开发心得
Easy to use shortcut keys in idea
FairyGUI摇杆
Esp8266 connect onenet (old mqtt mode)
随机推荐
Lean product development - Lean Software Development & lean product development
FairyGUI人物状态弹窗
Acwing-116 pilot brother
Unity3D,阿里云服务器,平台配置
(1) Introduction Guide to R language - the first step of data analysis
[算法] 剑指offer2 golang 面试题7:数组中和为0的3个数字
The service robots that have been hyped by capital and the Winter Olympics are not just a flash in the pan
Idea problem record
[Leetcode15]三数之和
[leetcode15] sum of three numbers
Unity3D制作注册登录界面,并实现场景跳转
[算法] 剑指offer2 golang 面试题6:排序数组中的两个数字之和
PR 2021 quick start tutorial, first understanding the Premiere Pro working interface
There is no red exclamation mark after SVN update
FairyGUI簡單背包的制作
Conditional probability
Unity场景跳转及退出
PRIDE-PPPAR源码解析
Naive Bayesian theory derivation
[算法] 剑指offer2 golang 面试题8:和大于或等于k的最短子数组