File tree 2 files changed +97
-0
lines changed
lcof2/剑指 Offer II 040. 矩阵中最大的矩形
2 files changed +97
-0
lines changed Original file line number Diff line number Diff line change @@ -254,6 +254,57 @@ func largestRectangleArea(heights []int) int {
254
254
}
255
255
```
256
256
257
+ #### Swift
258
+
259
+ ``` swift
260
+ class Solution {
261
+ func maximalRectangle (_ matrix : [String ]) -> Int {
262
+ guard let firstRow = matrix.first else {
263
+ return 0
264
+ }
265
+
266
+ let n = firstRow.count
267
+ var heights = [Int ](repeating : 0 , count : n)
268
+ var ans = 0
269
+
270
+ for row in matrix {
271
+ for (j, char) in row.enumerated () {
272
+ if char == " 1" {
273
+ heights[j] += 1
274
+ } else {
275
+ heights[j] = 0
276
+ }
277
+ }
278
+ ans = max (ans, largestRectangleArea (heights))
279
+ }
280
+
281
+ return ans
282
+ }
283
+
284
+ private func largestRectangleArea (_ heights : [Int ]) -> Int {
285
+ var res = 0
286
+ let n = heights.count
287
+ var stack = [Int ]()
288
+ var left = [Int ](repeating : -1 , count : n)
289
+ var right = [Int ](repeating : n, count : n)
290
+
291
+ for i in 0 ..< n {
292
+ while ! stack.isEmpty && heights[stack.last ! ] >= heights[i] {
293
+ right[stack.removeLast ()] = i
294
+ }
295
+ left[i] = stack.isEmpty ? -1 : stack.last !
296
+ stack.append (i)
297
+ }
298
+
299
+ for i in 0 ..< n {
300
+ res = max (res, heights[i] * (right[i] - left[i] - 1 ))
301
+ }
302
+
303
+ return res
304
+ }
305
+ }
306
+ ```
307
+
257
308
<!-- tabs: end -->
258
309
259
310
<!-- solution: end -->
Original file line number Diff line number Diff line change
1
+ class Solution {
2
+ func maximalRectangle( _ matrix: [ String ] ) -> Int {
3
+ guard let firstRow = matrix. first else {
4
+ return 0
5
+ }
6
+
7
+ let n = firstRow. count
8
+ var heights = [ Int] ( repeating: 0 , count: n)
9
+ var ans = 0
10
+
11
+ for row in matrix {
12
+ for (j, char) in row. enumerated ( ) {
13
+ if char == " 1 " {
14
+ heights [ j] += 1
15
+ } else {
16
+ heights [ j] = 0
17
+ }
18
+ }
19
+ ans = max ( ans, largestRectangleArea ( heights) )
20
+ }
21
+
22
+ return ans
23
+ }
24
+
25
+ private func largestRectangleArea( _ heights: [ Int ] ) -> Int {
26
+ var res = 0
27
+ let n = heights. count
28
+ var stack = [ Int] ( )
29
+ var left = [ Int] ( repeating: - 1 , count: n)
30
+ var right = [ Int] ( repeating: n, count: n)
31
+
32
+ for i in 0 ..< n {
33
+ while !stack. isEmpty && heights [ stack. last!] >= heights [ i] {
34
+ right [ stack. removeLast ( ) ] = i
35
+ }
36
+ left [ i] = stack. isEmpty ? - 1 : stack. last!
37
+ stack. append ( i)
38
+ }
39
+
40
+ for i in 0 ..< n {
41
+ res = max ( res, heights [ i] * ( right [ i] - left[ i] - 1 ) )
42
+ }
43
+
44
+ return res
45
+ }
46
+ }
You can’t perform that action at this time.
0 commit comments