Skip to content

Commit adb5ecf

Browse files
committed
q209
1 parent 991f4cf commit adb5ecf

File tree

2 files changed

+60
-0
lines changed

2 files changed

+60
-0
lines changed

src/array/mod.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,3 @@
11
mod q35;
22
mod q27;
3+
mod q209;

src/array/q209.rs

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
//! 给定一个含有n个正整数的数组和一个正整数 target 。
2+
//!
3+
//! 找出该数组中满足其和 ≥ target 的长度最小的 连续子数组[numsl, numsl+1, ..., numsr-1, numsr] ,并返回其长度。如果不存在符合条件的子数组,返回 0 。
4+
//!
5+
//!
6+
//! 示例 1:
7+
//! ```
8+
//! 输入:target = 7, nums = [2,3,1,2,4,3]
9+
//! 输出:2
10+
//! 解释:子数组[4,3]是该条件下的长度最小的子数组。
11+
//! ```
12+
//! 示例 2:
13+
//! ```
14+
//! 输入:target = 4, nums = [1,4,4]
15+
//! 输出:1
16+
//! ```
17+
//! 示例 3:
18+
//! ```
19+
//! 输入:target = 11, nums = [1,1,1,1,1,1,1,1]
20+
//! 输出:0
21+
//! ```
22+
23+
struct Solution();
24+
impl Solution {
25+
pub fn min_sub_array_len(target: i32, nums: Vec<i32>) -> i32 {
26+
let mut result = usize::MAX;
27+
let mut left_index = 0;
28+
let mut sum = 0;
29+
30+
for right_index in 0..nums.len() {
31+
sum += nums[right_index];
32+
while sum >= target {
33+
result = result.min(right_index - left_index);
34+
sum -= nums[left_index];
35+
left_index+=1;
36+
}
37+
}
38+
39+
if result == usize::MAX {
40+
0
41+
} else {
42+
result as i32 + 1
43+
}
44+
}
45+
}
46+
47+
48+
49+
#[cfg(test)]
50+
mod tests {
51+
use super::*;
52+
53+
#[test] fn common_test() {
54+
assert_eq!(Solution::min_sub_array_len(7, vec![2,3,1,2,4,3]), 2);
55+
56+
57+
58+
}
59+
}

0 commit comments

Comments
 (0)