-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
0435-non-overlapping-intervals.c
41 lines (33 loc) · 1.18 KB
/
0435-non-overlapping-intervals.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
// Interval structure
struct Interval {
int start;
int end;
};
// Function to compare intervals for sorting
int compareIntervals(const void* a, const void* b) {
return ((struct Interval*)a)->end - ((struct Interval*)b)->end;
}
int eraseOverlapIntervals(int** intervals, int intervalsSize, int* intervalsColSize) {
if (intervalsSize <= 1) {
return 0;
}
// Create an array of Interval structures
struct Interval* sortedIntervals = (struct Interval*)malloc(sizeof(struct Interval) * intervalsSize);
for (int i = 0; i < intervalsSize; i++) {
sortedIntervals[i].start = intervals[i][0];
sortedIntervals[i].end = intervals[i][1];
}
// Sort intervals based on end times
qsort(sortedIntervals, intervalsSize, sizeof(struct Interval), compareIntervals);
int end = sortedIntervals[0].end;
int nonOverlapCount = 1;
for (int i = 1; i < intervalsSize; i++) {
if (sortedIntervals[i].start >= end) {
end = sortedIntervals[i].end;
nonOverlapCount++;
}
}
free(sortedIntervals);
// Return the count of overlapping intervals to be removed
return intervalsSize - nonOverlapCount;
}