Skip to content

Commit 6c115d0

Browse files
authoredMay 13, 2024
feat: add swift implementation to lcci problem: No.17.21 (doocs#2808)
1 parent 33ee2c6 commit 6c115d0

File tree

3 files changed

+93
-0
lines changed

3 files changed

+93
-0
lines changed
 

‎lcci/17.21.Volume of Histogram/README.md

+32
Original file line numberDiff line numberDiff 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 -->

‎lcci/17.21.Volume of Histogram/README_EN.md

+32
Original file line numberDiff line numberDiff 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 numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
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+
}

0 commit comments

Comments
 (0)