You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardexpand all lines: solution/0400-0499/0435.Non-overlapping Intervals/README_EN.md
+49-98
Original file line number
Diff line number
Diff line change
@@ -63,7 +63,18 @@ tags:
63
63
64
64
<!-- solution:start -->
65
65
66
-
### Solution 1
66
+
### Solution 1: Sorting + Greedy
67
+
68
+
We first sort the intervals in ascending order by their right boundary. We use a variable $\textit{pre}$ to record the right boundary of the previous interval and a variable $\textit{ans}$ to record the number of intervals that need to be removed. Initially, $\textit{ans} = \textit{intervals.length}$.
69
+
70
+
Then we iterate through the intervals. For each interval:
71
+
72
+
- If the left boundary of the current interval is greater than or equal to $\textit{pre}$, it means that this interval does not need to be removed. We directly update $\textit{pre}$ to the right boundary of the current interval and decrement $\textit{ans}$ by one;
73
+
- Otherwise, it means that this interval needs to be removed, and we do not need to update $\textit{pre}$ and $\textit{ans}$.
74
+
75
+
Finally, we return $\textit{ans}$.
76
+
77
+
The time complexity is $O(n \times \log n)$, and the space complexity is $O(\log n)$, where $n$ is the number of intervals.
0 commit comments