File tree Expand file tree Collapse file tree 3 files changed +93
-0
lines changed
lcci/17.21.Volume of Histogram Expand file tree Collapse file tree 3 files changed +93
-0
lines changed Original file line number Diff line number Diff line change @@ -156,6 +156,38 @@ public class Solution {
156156}
157157```
158158
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+
159191<!-- tabs: end -->
160192
161193<!-- end -->
Original file line number Diff line number Diff line change @@ -150,6 +150,38 @@ public class Solution {
150150}
151151```
152152
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+
153185<!-- tabs: end -->
154186
155187<!-- 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