File tree 2 files changed +79
-0
lines changed
lcof2/剑指 Offer II 039. 直方图最大矩形面积
2 files changed +79
-0
lines changed Original file line number Diff line number Diff line change @@ -235,6 +235,48 @@ function largestRectangleArea(heights: number[]): number {
235
235
}
236
236
```
237
237
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
+
238
280
<!-- tabs: end -->
239
281
240
282
<!-- solution: end -->
Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments