파비의 매일매일 공부기록

Today's Challenge 본문

Problem Solving/LeetCode

Today's Challenge

fabichoi 2022. 9. 30. 23:45

https://leetcode.com/problems/the-skyline-problem/

 

The Skyline Problem - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

조금 이해하기 어려운 소스였음.. SortedList()라는 걸 사용해서 품.

from sortedcontainers import SortedList

class Solution:
    def getSkyline(self, buildings: List[List[int]]) -> List[List[int]]:
        s_end = SortedList()
        sht = SortedList()
        res = []
        
        def insert_into_res(x, h):
            if res and res[-1][0] == x:
                res.pop()
            if not res or res[-1][1] != h:
                res.append((x,h))
        
        def handle_end_of_building():
            end, idx = s_end.pop(0)
            if sht[-1] == (buildings[idx][2], idx):
                sht.pop()
                insert_into_res(end, sht[-1][0] if sht else 0)
            else:
                sht.remove((buildings[idx][2], idx))
                
        for i, x in enumerate(buildings):
            x1, x2, y = x
            
            while s_end and s_end[0][0] <= x1:
                handle_end_of_building()
            
            s_end.add((x2, i))
            sht.add((y, i))
            
            insert_into_res(x1, sht[-1][0])
        
        while s_end:
            handle_end_of_building()
        
        return res
반응형

'Problem Solving > LeetCode' 카테고리의 다른 글

Today's Challenge  (0) 2022.10.02
Today's Challenge  (0) 2022.10.01
Today's Challenge  (0) 2022.09.29
Today's Challenge  (0) 2022.09.28
Today's Challenge  (0) 2022.09.27
Comments