Skip to content

Commit

Permalink
Feat: 435. Non-overlapping Intervals
Browse files Browse the repository at this point in the history
  • Loading branch information
HC-kang committed Nov 7, 2024
1 parent ef9182e commit 0498b47
Showing 1 changed file with 29 additions and 0 deletions.
29 changes: 29 additions & 0 deletions non-overlapping-intervals/HC-kang.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
/**
* https://leetcode.com/problems/non-overlapping-intervals
* T.C. O(n logn)
* S.C. O(1)
*
* [[1,2],[2,3],[3,4],[1,3]] =(sort by end)=> [[1,2],[2,3],[1,3],[3,4]]
*
* 0 1 2 3 4...
* [=) pass
* [=) pass
* [===) count++
* ^^^
* [=) pass
*/
function eraseOverlapIntervals(intervals: number[][]): number {
intervals.sort((a, b) => a[1] - b[1]);

let count = 0;
let end = -Infinity;

for (let i = 0; i < intervals.length; i++) {
if (intervals[i][0] < end) { //
count++;
} else {
end = intervals[i][1];
}
}
return count;
}

0 comments on commit 0498b47

Please sign in to comment.