mirror of
https://github.com/halfrost/LeetCode-Go.git
synced 2025-07-08 02:15:01 +08:00
规范格式
This commit is contained in:
@ -0,0 +1,32 @@
|
||||
package leetcode
|
||||
|
||||
func minSubArrayLen(s int, nums []int) int {
|
||||
n := len(nums)
|
||||
if n == 0 {
|
||||
return 0
|
||||
}
|
||||
left, right, res, sum := 0, -1, n+1, 0
|
||||
for left < n {
|
||||
if (right+1) < n && sum < s {
|
||||
right++
|
||||
sum += nums[right]
|
||||
} else {
|
||||
sum -= nums[left]
|
||||
left++
|
||||
}
|
||||
if sum >= s {
|
||||
res = min(res, right-left+1)
|
||||
}
|
||||
}
|
||||
if res == n+1 {
|
||||
return 0
|
||||
}
|
||||
return res
|
||||
}
|
||||
|
||||
func min(a int, b int) int {
|
||||
if a > b {
|
||||
return b
|
||||
}
|
||||
return a
|
||||
}
|
@ -0,0 +1,43 @@
|
||||
package leetcode
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
)
|
||||
|
||||
type question209 struct {
|
||||
para209
|
||||
ans209
|
||||
}
|
||||
|
||||
// para 是参数
|
||||
// one 代表第一个参数
|
||||
type para209 struct {
|
||||
s int
|
||||
one []int
|
||||
}
|
||||
|
||||
// ans 是答案
|
||||
// one 代表第一个答案
|
||||
type ans209 struct {
|
||||
one int
|
||||
}
|
||||
|
||||
func Test_Problem209(t *testing.T) {
|
||||
|
||||
qs := []question209{
|
||||
|
||||
question209{
|
||||
para209{7, []int{2, 3, 1, 2, 4, 3}},
|
||||
ans209{2},
|
||||
},
|
||||
}
|
||||
|
||||
fmt.Printf("------------------------Leetcode Problem 209------------------------\n")
|
||||
|
||||
for _, q := range qs {
|
||||
_, p := q.ans209, q.para209
|
||||
fmt.Printf("【input】:%v 【output】:%v\n", p, minSubArrayLen(p.s, p.one))
|
||||
}
|
||||
fmt.Printf("\n\n\n")
|
||||
}
|
26
leetcode/0209.Minimum-Size-Subarray-Sum/README.md
Normal file
26
leetcode/0209.Minimum-Size-Subarray-Sum/README.md
Normal file
@ -0,0 +1,26 @@
|
||||
# [209. Minimum Size Subarray Sum](https://leetcode.com/problems/minimum-size-subarray-sum/)
|
||||
|
||||
## 题目
|
||||
|
||||
Given an array of n positive integers and a positive integer s, find the minimal length of a contiguous subarray of which the sum ≥ s. If there isn't one, return 0 instead.
|
||||
|
||||
Example 1:
|
||||
|
||||
```c
|
||||
Input: s = 7, nums = [2,3,1,2,4,3]
|
||||
Output: 2
|
||||
Explanation: the subarray [4,3] has the minimal length under the problem constraint.
|
||||
```
|
||||
|
||||
Follow up:
|
||||
|
||||
If you have figured out the O(n) solution, try coding another solution of which the time complexity is O(n log n).
|
||||
|
||||
## 题目大意
|
||||
|
||||
给定一个整型数组和一个数字 s,找到数组中最短的一个连续子数组,使得连续子数组的数字之和 sum>=s,返回最短的连续子数组的返回值。
|
||||
|
||||
## 解题思路
|
||||
|
||||
这一题的解题思路是用滑动窗口。在滑动窗口 [i,j]之间不断往后移动,如果总和小于 s,就扩大右边界 j,不断加入右边的值,直到 sum > s,之和再缩小 i 的左边界,不断缩小直到 sum < s,这时候右边界又可以往右移动。以此类推。
|
||||
|
Reference in New Issue
Block a user