Skip to content

Commit 9dd6fb9

Browse files
authored
Merge pull request neetcode-gh#2851 from mdmzfzl/main
Create: 0435-non-overlapping-intervals.c
2 parents 1332bdd + 5bed29e commit 9dd6fb9

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

c/0435-non-overlapping-intervals.c

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
// Interval structure
2+
struct Interval {
3+
int start;
4+
int end;
5+
};
6+
7+
// Function to compare intervals for sorting
8+
int compareIntervals(const void* a, const void* b) {
9+
return ((struct Interval*)a)->end - ((struct Interval*)b)->end;
10+
}
11+
12+
int eraseOverlapIntervals(int** intervals, int intervalsSize, int* intervalsColSize) {
13+
if (intervalsSize <= 1) {
14+
return 0;
15+
}
16+
17+
// Create an array of Interval structures
18+
struct Interval* sortedIntervals = (struct Interval*)malloc(sizeof(struct Interval) * intervalsSize);
19+
for (int i = 0; i < intervalsSize; i++) {
20+
sortedIntervals[i].start = intervals[i][0];
21+
sortedIntervals[i].end = intervals[i][1];
22+
}
23+
24+
// Sort intervals based on end times
25+
qsort(sortedIntervals, intervalsSize, sizeof(struct Interval), compareIntervals);
26+
27+
int end = sortedIntervals[0].end;
28+
int nonOverlapCount = 1;
29+
30+
for (int i = 1; i < intervalsSize; i++) {
31+
if (sortedIntervals[i].start >= end) {
32+
end = sortedIntervals[i].end;
33+
nonOverlapCount++;
34+
}
35+
}
36+
37+
free(sortedIntervals);
38+
39+
// Return the count of overlapping intervals to be removed
40+
return intervalsSize - nonOverlapCount;
41+
}

0 commit comments

Comments
 (0)