@@ -926,6 +926,56 @@ int trap(int* height, int heightSize) {
926
926
* 空间复杂度 O(1)
927
927
928
928
929
+ Rust
930
+
931
+ 双指针
932
+
933
+ ```rust
934
+ impl Solution {
935
+ pub fn trap(height: Vec<i32>) -> i32 {
936
+ let n = height.len();
937
+ let mut max_left = vec![0; height.len()];
938
+ let mut max_right = vec![0; height.len()];
939
+ max_left.iter_mut().zip(max_right.iter_mut().rev()).enumerate().fold((0, 0), |(lm, rm), (idx, (x, y))| {
940
+ let lmax = lm.max(height[idx]);
941
+ let rmax = rm.max(height[n - 1 - idx]);
942
+ *x = lmax; *y = rmax;
943
+ (lmax, rmax)
944
+ });
945
+ height.iter().enumerate().fold(0, |acc, (idx, x)| {
946
+ let h = max_left[idx].min(max_right[idx]);
947
+ if h > 0 { h - x + acc } else { acc }
948
+ })
949
+ }
950
+ }
951
+ ```
952
+
953
+ 单调栈
954
+
955
+ ``` rust
956
+ impl Solution {
957
+ pub fn trap (height : Vec <i32 >) -> i32 {
958
+ let mut stack = vec! [];
959
+ let mut ans = 0 ;
960
+ for (right_pos , & right_h ) in height . iter (). enumerate () {
961
+ while ! stack . is_empty () && height [* stack . last (). unwrap ()] <= right_h {
962
+ let mid_pos = stack . pop (). unwrap ();
963
+ if ! stack . is_empty () {
964
+ let left_pos = * stack . last (). unwrap ();
965
+ let left_h = height [left_pos ];
966
+ let top = std :: cmp :: min (left_h , right_h );
967
+ if top > height [mid_pos ] {
968
+ ans += (top - height [mid_pos ]) * (right_pos - left_pos - 1 ) as i32 ;
969
+ }
970
+ }
971
+ }
972
+ stack . push (right_pos );
973
+ }
974
+ ans
975
+ }
976
+ }
977
+ ```
978
+
929
979
<p align =" center " >
930
980
<a href =" https://programmercarl.com/other/kstar.html " target =" _blank " >
931
981
<img src =" ../pics/网站星球宣传海报.jpg " width =" 1000 " />
0 commit comments