Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit f224c66

Browse files
feat: add swift implementation to lcof2 problem: No.039 (doocs#3049)
1 parent 23858da commit f224c66

File tree

2 files changed

+79
-0
lines changed

2 files changed

+79
-0
lines changed

‎lcof2/剑指 Offer II 039. 直方图最大矩形面积/README.md‎

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -235,6 +235,48 @@ function largestRectangleArea(heights: number[]): number {
235235
}
236236
```
237237

238+
#### Swift
239+
240+
```swift
241+
class Solution {
242+
func largestRectangleArea(_ heights: [Int]) -> Int {
243+
let n = heights.count
244+
var left = [Int](repeating: -1, count: n)
245+
var right = [Int](repeating: n, count: n)
246+
var stack = [Int]()
247+
248+
for i in 0..<n {
249+
while !stack.isEmpty && heights[stack.last!] >= heights[i] {
250+
stack.removeLast()
251+
}
252+
if !stack.isEmpty {
253+
left[i] = stack.last!
254+
}
255+
stack.append(i)
256+
}
257+
258+
stack.removeAll()
259+
260+
for i in stride(from: n - 1, through: 0, by: -1) {
261+
while !stack.isEmpty && heights[stack.last!] >= heights[i] {
262+
stack.removeLast()
263+
}
264+
if !stack.isEmpty {
265+
right[i] = stack.last!
266+
}
267+
stack.append(i)
268+
}
269+
270+
var maxArea = 0
271+
for i in 0..<n {
272+
maxArea = max(maxArea, (right[i] - left[i] - 1) * heights[i])
273+
}
274+
275+
return maxArea
276+
}
277+
}
278+
```
279+
238280
<!-- tabs:end -->
239281

240282
<!-- solution:end -->
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
class Solution {
2+
func largestRectangleArea(_ heights: [Int]) -> Int {
3+
let n = heights.count
4+
var left = [Int](repeating: -1, count: n)
5+
var right = [Int](repeating: n, count: n)
6+
var stack = [Int]()
7+
8+
for i in 0..<n {
9+
while !stack.isEmpty && heights[stack.last!] >= heights[i] {
10+
stack.removeLast()
11+
}
12+
if !stack.isEmpty {
13+
left[i] = stack.last!
14+
}
15+
stack.append(i)
16+
}
17+
18+
stack.removeAll()
19+
20+
for i in stride(from: n - 1, through: 0, by: -1) {
21+
while !stack.isEmpty && heights[stack.last!] >= heights[i] {
22+
stack.removeLast()
23+
}
24+
if !stack.isEmpty {
25+
right[i] = stack.last!
26+
}
27+
stack.append(i)
28+
}
29+
30+
var maxArea = 0
31+
for i in 0..<n {
32+
maxArea = max(maxArea, (right[i] - left[i] - 1) * heights[i])
33+
}
34+
35+
return maxArea
36+
}
37+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /