1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
| class Solution { func getSkyline(_ buildings: [[Int]]) -> [[Int]] { let n = buildings.count if n == 0 { return [] } if n == 1 { return [[buildings[0][0], buildings[0][2]], [buildings[0][1], 0]] } let l = getSkyline(Array(buildings[..<(n/2)])) let r = getSkyline(Array(buildings[(n/2)...])) return merge(l, r) }
private func merge(_ l: [[Int]], _ r: [[Int]]) -> [[Int]] { let ln = l.count, rn = r.count var lp = 0, rp = 0 var curY = 0, lY = 0, rY = 0 , output = [[Int]]() func update(_ x: Int, _ y: Int) { if output.isEmpty || output.last?.first != x { output.append([x, y]) } else { output[output.count-1][1] = y } } func append(_ p: Int, _ lst: [[Int]], _ n: Int, _ curY: Int) { var p = p, curY = curY while p < n { let (x, y) = (lst[p][0], lst[p][1]) p += 1 if curY != y { update(x, y) curY = y } } } while lp < ln && rp < rn { let lPoint = l[lp], rPoint = r[rp] var x = 0 if lPoint[0] < rPoint[0] { (x, lY) = (lPoint[0], lPoint[1]) lp += 1 } else { (x, rY) = (rPoint[0], rPoint[1]) rp += 1 } let maxY = max(lY, rY) if curY != maxY { update(x, maxY) curY = maxY } } append(lp, l, ln, curY) append(rp, r, rn, curY) return output } }
|