Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- Observation:Change is only possible at building start or end.
- so break the starting and ending point of building where height at starting point will be positive of height
- and at ending point negative height so that we can differentiate between starting and ending point.
- eg (2,9,13) -> (2,13) and (9,-13)
- sort the above list because answer asked in question is in sorted order.
- Let's say building present at current point is active buildings so,outline is maximum height among active buildings.
- so we maintain a max_heap which will maintain the maximum height building at top and that building is active or not,
- that can be taken care by map.
- so whenever we see positive height,means start of building then
- if it's abs(height)>cur_height push it into answer,active building and map and also update the current_height.
- if it's abs(height)<=cur_height push it into active building and map
- if current height is negative means end of building:
- if it's height is same as cur_height,then remove that height from map,and find the maximum height among the
- active buildings and update the cur_height if cur_height is different and update the answer else keep it same
- Test Case: [[0,2,3],[2,5,3]]
- else remove from map.
- One more example is : [0,2],[2,-2],[2,2],[4,-2] ans : [0,2],[4,0]
- here first building is ending at point 2 and second building is starting again at 2 so while sorting we will add first so my_fun is created otherwise answer in our above example will be at 2 is [2,0] then again go to [2,2].
- from heapq import heapify,heappush,heappop
- def my_fun(a):
- return a[0],-a[1]
- class Solution:
- def getSkyline(self, buil: List[List[int]]) -> List[List[int]]:
- arr=[]
- dict={}
- heap=[]
- heapify(heap)
- for i in buil:
- arr.append([i[0],i[2]])
- arr.append([i[1],-i[2]])
- arr.sort(key=my_fun)
- cur_height=0
- ans=[]
- for i in arr:
- if i[1]>0: #means start of the building
- if i[1]>cur_height:
- ans.append([i[0],i[1]])
- cur_height=i[1]
- heappush(heap,-1*i[1])
- if i[1] in dict.keys():
- dict[i[1]]+=1
- else:
- dict[i[1]]=1
- elif i[1]<=cur_height:
- heappush(heap,-i[1])
- if i[1] in dict.keys():
- dict[i[1]]+=1
- else:
- dict[i[1]]=1
- else:
- dict[abs(i[1])]-=1
- while len(heap)>0 and dict[abs(heap[0])]<=0:
- heappop(heap)
- if len(heap)>0:
- cur=abs(heap[0])
- else:
- cur=0
- if cur!=cur_height:
- ans.append([i[0],cur])
- cur_height=cur
- return ans
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement