File tree 3 files changed +93
-0
lines changed
lcci/17.21.Volume of Histogram
3 files changed +93
-0
lines changed Original file line number Diff line number Diff line change @@ -156,6 +156,38 @@ public class Solution {
156
156
}
157
157
```
158
158
159
+ ``` swift
160
+ class Solution {
161
+ func trap (_ height : [Int ]) -> Int {
162
+ let n = height.count
163
+ if n < 3 {
164
+ return 0
165
+ }
166
+
167
+ var left = [Int ](repeating : 0 , count : n)
168
+ var right = [Int ](repeating : 0 , count : n)
169
+
170
+ left[0 ] = height[0 ]
171
+ right[n - 1 ] = height[n - 1 ]
172
+
173
+ for i in 1 ..< n {
174
+ left[i] = max (left[i - 1 ], height[i])
175
+ }
176
+
177
+ for i in stride (from : n - 2 , through : 0 , by : -1 ) {
178
+ right[i] = max (right[i + 1 ], height[i])
179
+ }
180
+
181
+ var ans = 0
182
+ for i in 0 ..< n {
183
+ ans += min (left[i], right[i]) - height[i]
184
+ }
185
+
186
+ return ans
187
+ }
188
+ }
189
+ ```
190
+
159
191
<!-- tabs: end -->
160
192
161
193
<!-- end -->
Original file line number Diff line number Diff line change @@ -150,6 +150,38 @@ public class Solution {
150
150
}
151
151
```
152
152
153
+ ``` swift
154
+ class Solution {
155
+ func trap (_ height : [Int ]) -> Int {
156
+ let n = height.count
157
+ if n < 3 {
158
+ return 0
159
+ }
160
+
161
+ var left = [Int ](repeating : 0 , count : n)
162
+ var right = [Int ](repeating : 0 , count : n)
163
+
164
+ left[0 ] = height[0 ]
165
+ right[n - 1 ] = height[n - 1 ]
166
+
167
+ for i in 1 ..< n {
168
+ left[i] = max (left[i - 1 ], height[i])
169
+ }
170
+
171
+ for i in stride (from : n - 2 , through : 0 , by : -1 ) {
172
+ right[i] = max (right[i + 1 ], height[i])
173
+ }
174
+
175
+ var ans = 0
176
+ for i in 0 ..< n {
177
+ ans += min (left[i], right[i]) - height[i]
178
+ }
179
+
180
+ return ans
181
+ }
182
+ }
183
+ ```
184
+
153
185
<!-- tabs: end -->
154
186
155
187
<!-- end -->
Original file line number Diff line number Diff line change
1
+ class Solution {
2
+ func trap( _ height: [ Int ] ) -> Int {
3
+ let n = height. count
4
+ if n < 3 {
5
+ return 0
6
+ }
7
+
8
+ var left = [ Int] ( repeating: 0 , count: n)
9
+ var right = [ Int] ( repeating: 0 , count: n)
10
+
11
+ left [ 0 ] = height [ 0 ]
12
+ right [ n - 1 ] = height [ n - 1 ]
13
+
14
+ for i in 1 ..< n {
15
+ left [ i] = max ( left [ i - 1 ] , height [ i] )
16
+ }
17
+
18
+ for i in stride ( from: n - 2 , through: 0 , by: - 1 ) {
19
+ right [ i] = max ( right [ i + 1 ] , height [ i] )
20
+ }
21
+
22
+ var ans = 0
23
+ for i in 0 ..< n {
24
+ ans += min ( left [ i] , right [ i] ) - height[ i]
25
+ }
26
+
27
+ return ans
28
+ }
29
+ }
You can’t perform that action at this time.
0 commit comments