File tree Expand file tree Collapse file tree 1 file changed +56
-0
lines changed Expand file tree Collapse file tree 1 file changed +56
-0
lines changed Original file line number Diff line number Diff line change @@ -101,3 +101,59 @@ impl Solution {
101
101
102
102
所以这个引用就不要自动匹配掉了,就手动解引用吧
103
103
104
+
105
+ 思路:前缀和+双指针
106
+
107
+ ``` rust
108
+ # struct Solution {}
109
+ impl Solution {
110
+ pub fn min_sub_array_len (target : i32 , nums : Vec <i32 >) -> i32 {
111
+ // prefix sum
112
+ let pre_sum : Vec <i32 > = nums . iter (). scan (0i32 , | st , & x | {
113
+ * st += x ;
114
+ Some (* st )
115
+ }). collect ();
116
+ let idx : usize = pre_sum . partition_point (| & x | x < target );
117
+ if idx == nums . len () { return 0i32 }
118
+ let mut res : usize = idx + 1usize ;
119
+ let mut right : usize = idx ;
120
+ let mut left : usize = 0usize ;
121
+ while right < nums . len () {
122
+ while pre_sum [right ] - pre_sum [left ] >= target {
123
+ left += 1usize ;
124
+ }
125
+ let candidate : usize = right - left + 1usize ;
126
+ res = std :: cmp :: min (candidate , res );
127
+ right += 1usize ;
128
+ }
129
+ res as i32
130
+ }
131
+ }
132
+ ```
133
+
134
+
135
+
136
+ ``` rust
137
+
138
+ # struct Solution {}
139
+
140
+ impl Solution {
141
+ pub fn min_sub_array_len (target : i32 , nums : Vec <i32 >) -> i32 {
142
+ let mut sum : i32 = 0i32 ;
143
+ let mut left : usize = 0usize ;
144
+ let mut res : usize = usize :: MAX ;
145
+ for right in 0usize .. nums . len () {
146
+ sum += nums [right ];
147
+ while sum >= target {
148
+ res = std :: cmp :: min (res , right - left + 1usize );
149
+ sum -= nums [left ];
150
+ left += 1usize ;
151
+ }
152
+ }
153
+ match res {
154
+ usize :: MAX => 0 ,
155
+ _ => res as i32 ,
156
+ }
157
+ }
158
+ }
159
+ ```
You can’t perform that action at this time.
0 commit comments