当前位置:网站首页>209. Subarray with the smallest length
209. Subarray with the smallest length
2022-07-26 08:59:00 【apprentice.】
subject :
Answer key :
For this question , There is a word in the question that requires Continuous subarray , For this requirement continuous , Sliding windows should be considered first . Then the question is to find the shortest continuous sub array, so when traversing this array , The general idea is as follows :
- Combination of values in the window < target : The length of the window +1
- Combination of values in the window >= target : Compare the current window length with the shortest length recorded , And the window length -1
For window length +1 operation , Is to expand an element on the right side of the window , For window length -1 The operation of , Is to subtract an element from the left
Here are Go The language code :
func minSubArrayLen(target int, nums []int) int {
min := len(nums) + 1
winLen := 1
sum := nums[0]
for i := 0; ; {
if sum < target {
if i+winLen == len(nums) {
break
}
winLen++
sum = sum + nums[i+winLen-1]
}
if sum >= target {
if winLen < min {
min = winLen
}
sum = sum - nums[i]
i++
winLen--
}
}
if min == len(nums)+1 {
return 0
} else {
return min
}
}
边栏推荐
猜你喜欢
随机推荐
Cadence (x) wiring skills and precautions
zsh: command not found: nvm
Dynamic SQL and exceptions of pl/sql
JDBC数据库连接池(Druid技术)
SSH,NFS,FTP
JDBC database connection pool (Druid Technology)
Solve the problem of C # calling form controls across threads
Web overview and b/s architecture
[suggestions collection] summary of MySQL 30000 word essence - locking mechanism and performance tuning (IV) [suggestions collection]
Set of pl/sql
PXE principles and concepts
What are the differences in the performance of different usages such as count (*), count (primary key ID), count (field) and count (1)? That's more efficient
P1825 [USACO11OPEN]Corn Maze S
Study notes of automatic control principle -- correction and synthesis of automatic control system
pl/sql之集合-2
day06 作业--增删改查
(1) CTS tradefed test framework environment construction
Form form
Learning notes of automatic control principle - Performance Analysis of continuous time system
Human computer interaction software based on C language