Leetcode 218 skyline problem
-
thinking
It can be seen as a merging problem
During segmentation, if there is only one element left, return the two contour points it represents. If it is blank, return null
Consolidation is the focus:
-
Maintain two variables: h1,h2 h1 represents the current position height of the left half, h2 represents the current position height of the right half
-
If the abscissa of the left half of the current position is smaller, update h1 and select elements from the left half;
-
If the abscissa of the right half of the current position is smaller, update h2 and select elements from the right half;
-
If it is the same size, update h1,h2 and select elements from the left (or right) half
-
When you insert a point into the result, only points that are different in height from the last point in the result can be inserted into the result
And always use the height max(h1,h2).
-
When one part is completely accessed, insert the other part directly into the result (note that the height should not be the same as before).
-
-
AC code
class Solution(object): def mergeSort(self, arr): if len(arr) <= 0: return None if len(arr) == 1: return [[arr[0][0], arr[0][2]], [arr[0][1], 0]] n = len(arr) middle = n / 2 one = self.mergeSort(arr[:middle]) two = self.mergeSort(arr[middle:]) if one == None: return two if two == None: return one #Merge two arrays h record current height i, j, h1, h2, before = 0, 0, -1, -1, -1 data = [] while i < len(one) and j < len(two): if one[i][0] < two[j][0]: h1 = one[i][1] if max(h1, h2) != before: data.append([one[i][0], max(h1,h2)]) before = max(h1, h2) i += 1 elif one[i][0] > two[j][0]: h2 = two[j][1] if max(h1, h2) != before: data.append([two[j][0], max(h1, h2)]) before = max(h1, h2) j += 1 else: h1 = one[i][1]; h2 = two[j][1] if max(h1, h2) != before: data.append([one[i][0], max(h1, h2)]) before = max(h1, h2) i += 1 while i < len(one): if one[i][1] != before: data.append([one[i][0], one[i][1]]) before = one[i][1] i += 1 while j < len(two): if two[j][1] != before: data.append([two[j][0], two[j][1]]) before = two[j][1] j += 1 return data def getSkyline(self, buildings): """ :type buildings: List[List[int]] :rtype: List[List[int]] """ if buildings == []: return [] return self.mergeSort(buildings)