leetcode-218-天际线问题
题目描述:
方法一:分治 O(nlogn)
class Solution: def getSkyline(self, buildings: List[List[int]]) -> List[List[int]]: if not buildings:return [] if len(buildings)==1: return [[buildings[0][0], buildings[0][2]], [buildings[0][1], 0]] mid = len(buildings)//2 left = self.getSkyline(buildings[:mid]) right = self.getSkyline(buildings[mid:]) return self.merge(left,right) def merge(self,left,right): l,r = 0,0 lh,rh = 0,0 res = [] while l<len(left) and r<len(right): if left[l][0]<right[r][0]: cp = [left[l][0], max(left[l][1], rh)] lh = left[l][1] l += 1 elif left[l][0] > right[r][0]: cp = [right[r][0], max(right[r][1], lh)] rh = right[r][1] r += 1 # 相等情况 else: cp = [left[l][0], max(left[l][1], right[r][1])] lh = left[l][1] rh = right[r][1] l += 1 r += 1 if len(res)==0 or res[-1][1]!=cp[1]: res.append(cp) res.extend(left[l:] or right[r:]) return res
方法二:
class Solution: def getSkyline(self, buildings: List[List[int]]) -> List[List[int]]: import bisect res = [[0, 0]] # 记录 [left, height], [right, height] loc = [] for l, r, h in buildings: # 为了排序让 left那边靠前, 所以让高度取负 loc.append([l, -h]) loc.append([r, h]) loc.sort() heap = [0] for x, h in loc: if h < 0: bisect.insort(heap, h) else: heap.remove(-h) cur = -heap[0] if res[-1][1] != cur: res.append([x, cur]) return res[1:]
方法三:堆*
class Solution: def getSkyline(self, buildings): import heapq events = sorted([(L, -H, R) for L, R, H in buildings] + list({(R, 0, 0) for _, R, _ in buildings } )) res = [[0, 0]] heap = [[0, float("inf")]] for x, H, R in events: while x >= heap[0][1]: heapq.heappop(heap) if H: heapq.heappush(heap, [H, R]) if res[-1][1] != -heap[0][0]: res.append([x, -heap[0][0]]) return res[1:]