Advertisement
HXXXXJ

218. The Skyline Problem - 简单做法

Apr 14th, 2019
203
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 1.39 KB | None | 0 0
  1. func getSkyline(_ buildings: [[Int]]) -> [[Int]] {
  2.         var lines = [(Int, Int, Bool)]() // index, height, isstart
  3.        
  4.         for b in buildings{
  5.             lines.append((b[0], b[2],true))
  6.             lines.append((b[1], b[2], false))
  7.         }
  8.         lines.sort{
  9.             if $0.0 != $1.0 {return $0.0 < $1.0 }
  10.             else if $0.2 == false { return false }
  11.             return true
  12.         }
  13.         var res = [[Int]]()
  14.         var heap = Heap<Int>(.max)
  15.         var lastH = 0
  16.  /**
  17. 最后进入结果的坐标改变必须复合这两条, 缺一不可
  18. 1. Index 变了
  19. 2. height 变了
  20. 所以对于每个数据点。 在index相同的时候, 我们只能丢入heap中保存
  21. 当Index要变化的时候, 我们才去check height变化。 - 和之前的height作比较
  22. **/
  23.  
  24.  
  25.         for i in 0 ..< lines.count {
  26.             var l = lines[i]
  27.             if i != 0 && l.0 != lines[i-1].0 {
  28.                 let currentH = heap.count > 0 ? heap.peek()! : 0
  29.                 if currentH != lastH {
  30.                     res.append([lines[i-1].0, currentH])
  31.                     lastH = currentH
  32.                 }
  33.             }
  34.             if l.2 {
  35.                 heap.insert(l.1)
  36.             }else {
  37.                 heap.remove(l.1)
  38.             }
  39.             if i == lines.count - 1 {
  40.                 res.append([l.0, 0])
  41.             }
  42.         }
  43.         return res
  44.     }
  45. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement