Skip to content

Commit

Permalink
re-solve "56. Merge Intervals"
Browse files Browse the repository at this point in the history
  • Loading branch information
lancelote committed Oct 13, 2024
1 parent 2887b36 commit bdb9d9d
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 13 deletions.
4 changes: 4 additions & 0 deletions .plan
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,10 @@ Backlog
solve all "intervals" questions in top-150
complete top interview 150

Oct 13, 2024

* re-solve "56. Merge Intervals"

Oct 12, 2024

* solve all "matrix" questions in top-150
Expand Down
19 changes: 6 additions & 13 deletions src/merge_intervals.py
Original file line number Diff line number Diff line change
@@ -1,22 +1,15 @@
class Solution:
def merge(self, intervals: list[list[int]]) -> list[list[int]]:
assert intervals

n = len(intervals)
result: list[list[int]] = []
intervals = sorted(intervals, key=lambda x: x[0])

tmp_start, tmp_end = intervals[0]
sorted_intervals = sorted(intervals)
result: list[list[int]] = [sorted_intervals[0]]

for i in range(1, n):
start, end = intervals[i]
left, right = sorted_intervals[i]

if start <= tmp_end:
tmp_end = max(end, tmp_end)
if result[-1][1] >= left:
result[-1][1] = max(result[-1][1], right)
else:
result.append([tmp_start, tmp_end])
tmp_start = start
tmp_end = end
result.append([left, right])

result.append([tmp_start, tmp_end])
return result

0 comments on commit bdb9d9d

Please sign in to comment.