File tree 3 files changed +88
-0
lines changed
solution/0000-0099/0042.Trapping Rain Water
3 files changed +88
-0
lines changed Original file line number Diff line number Diff line change @@ -113,6 +113,37 @@ public:
113
113
};
114
114
```
115
115
116
+ ### **Rust**
117
+
118
+ ```rust
119
+ impl Solution {
120
+ #[allow(dead_code)]
121
+ pub fn trap(height: Vec<i32>) -> i32 {
122
+ let n = height.len();
123
+ let mut left: Vec<i32> = vec![0; n];
124
+ let mut right: Vec<i32> = vec![0; n];
125
+
126
+ left[0] = height[0];
127
+ right[n - 1] = height[n - 1];
128
+
129
+ // Initialize the left & right vector
130
+ for i in 1..n {
131
+ left[i] = std::cmp::max(left[i - 1], height[i]);
132
+ right[n - i - 1] = std::cmp::max(right[n - i], height[n - i - 1]);
133
+ }
134
+
135
+ let mut ans = 0;
136
+
137
+ // Calculate the ans
138
+ for i in 0..n {
139
+ ans += std::cmp::min(left[i], right[i]) - height[i];
140
+ }
141
+
142
+ ans
143
+ }
144
+ }
145
+ ```
146
+
116
147
### ** Go**
117
148
118
149
``` go
Original file line number Diff line number Diff line change @@ -101,6 +101,37 @@ public:
101
101
};
102
102
```
103
103
104
+ ### **Rust**
105
+
106
+ ```rust
107
+ impl Solution {
108
+ #[allow(dead_code)]
109
+ pub fn trap(height: Vec<i32>) -> i32 {
110
+ let n = height.len();
111
+ let mut left: Vec<i32> = vec![0; n];
112
+ let mut right: Vec<i32> = vec![0; n];
113
+
114
+ left[0] = height[0];
115
+ right[n - 1] = height[n - 1];
116
+
117
+ // Initialize the left & right vector
118
+ for i in 1..n {
119
+ left[i] = std::cmp::max(left[i - 1], height[i]);
120
+ right[n - i - 1] = std::cmp::max(right[n - i], height[n - i - 1]);
121
+ }
122
+
123
+ let mut ans = 0;
124
+
125
+ // Calculate the ans
126
+ for i in 0..n {
127
+ ans += std::cmp::min(left[i], right[i]) - height[i];
128
+ }
129
+
130
+ ans
131
+ }
132
+ }
133
+ ```
134
+
104
135
### ** Go**
105
136
106
137
``` go
Original file line number Diff line number Diff line change
1
+ impl Solution {
2
+ #[ allow( dead_code) ]
3
+ pub fn trap ( height : Vec < i32 > ) -> i32 {
4
+ let n = height. len ( ) ;
5
+ let mut left: Vec < i32 > = vec ! [ 0 ; n] ;
6
+ let mut right: Vec < i32 > = vec ! [ 0 ; n] ;
7
+
8
+ left[ 0 ] = height[ 0 ] ;
9
+ right[ n - 1 ] = height[ n - 1 ] ;
10
+
11
+ // Initialize the left & right vector
12
+ for i in 1 ..n {
13
+ left[ i] = std:: cmp:: max ( left[ i - 1 ] , height[ i] ) ;
14
+ right[ n - i - 1 ] = std:: cmp:: max ( right[ n - i] , height[ n - i - 1 ] ) ;
15
+ }
16
+
17
+ let mut ans = 0 ;
18
+
19
+ // Calculate the ans
20
+ for i in 0 ..n {
21
+ ans += std:: cmp:: min ( left[ i] , right[ i] ) - height[ i] ;
22
+ }
23
+
24
+ ans
25
+ }
26
+ }
You can’t perform that action at this time.
0 commit comments