Scribbling

LeetCode: 56. Merge Intervals 본문

Computer Science/Coding Test

LeetCode: 56. Merge Intervals

focalpoint 2021. 9. 23. 11:47

Sorting ahead is the key here.

class Solution:
    def merge(self, intervals: List[List[int]]) -> List[List[int]]:
        intervals.sort(key=lambda x: (x[0], x[1]))
        ret = []
        for interval in intervals:
            if ret and ret[-1][0] <= interval[0] <= ret[-1][1]:
                ret[-1][1] = max(ret[-1][1], interval[1])
            else:
                ret.append(interval)
        return ret

'Computer Science > Coding Test' 카테고리의 다른 글

LeetCode: 53. Maximum Subarray  (0) 2021.09.24
LeetCode: 57. Insert Interval  (0) 2021.09.24
LeetCode: 54. Spiral Matrix  (1) 2021.09.17
LeetCode: 55. Jump Game  (0) 2021.09.15
LeetCode: 52. N-Queens II  (0) 2021.09.15