#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static int compare(const void *a, const void *b)
{
return ((int *) a)[0] - ((int *) b)[0];
}
/**
* Return an array of arrays of size *returnSize.
* The sizes of the arrays are returned as *returnColumnSizes array.
* Note: Both returned array and *returnColumnSizes array must be malloced, assume caller calls free().
*/
int** merge(int** intervals, int intervalsSize, int* intervalsColSize, int* returnSize, int** returnColumnSizes)
{
if (intervalsSize == 0) {
*returnSize = 0;
return intervals;
}
int i, len = 0;
int *tmp = malloc(intervalsSize * 2 * sizeof(int));
for (i = 0; i < intervalsSize; i++) {
tmp[i * 2] = intervals[i][0];
tmp[i * 2 + 1] = intervals[i][1];
}
qsort(tmp, intervalsSize, 2 * sizeof(int), compare);
intervals[0][0] = tmp[0];
intervals[0][1] = tmp[1];
for (i = 1; i < intervalsSize; i++) {
if (tmp[i * 2] > intervals[len][1]) {
len++;
intervals[len][0] = tmp[i * 2];
intervals[len][1] = tmp[i * 2 + 1];
} else if (tmp[i * 2 + 1] > intervals[len][1]) {
/* merge this interval */
intervals[len][1] = tmp[i * 2 + 1];
}
}
len += 1;
*returnSize = len;
*returnColumnSizes = malloc(len * sizeof(int));
for (i = 0; i < len; i++) {
(*returnColumnSizes)[i] = 2;
}
return intervals;
}
int main(int argc, char **argv)
{
if (argc < 1|| argc % 2 == 0) {
fprintf(stderr, "Usage: ./test s0 e0 s1 e1...");
exit(-1);
}
int i, count = 0;
int *sizes = malloc((argc - 1) / 2 * sizeof(int));
int **intervals = malloc((argc - 1) / 2 * sizeof(int *));
for (i = 0; i < (argc - 1) / 2; i++) {
sizes[i] = 2;
intervals[i] = malloc(2 * sizeof(int));
intervals[i][0] = atoi(argv[i * 2 + 1]);
intervals[i][1] = atoi(argv[i * 2 + 2]);
}
int *col_sizes;
int **results = merge(intervals, (argc - 1) / 2, sizes, &count, &col_sizes);
for (i = 0; i < count; i++) {
printf("[%d,%d]\n", results[i][0], results[i][1]);
}
return 0;
}
C语言入门-leetcode练习之第56题合并区间.zip
需积分: 1 146 浏览量
2024-05-27
04:47:22
上传
评论
收藏 2KB ZIP 举报
![avatar](https://profile-avatar.csdnimg.cn/3c54a849f48044a884c4cf76b8fda72a_weixin_66442839.jpg!1)
__AtYou__
- 粉丝: 1895
- 资源: 648
最新资源
- 苹果CMS红色red1电影影视主题网站模板
- 光大证券-20170725-阻力支撑相对强度(RSRS)选股-技术指标系列报告之三.pdf
- EMV 4.4 Book 1~4
- 1_pt_cfix .xlsx
- EMV 4.3 Book 1~4
- EMV 4.2 Book 1~4
- EMV 4.1 Book 1~4
- 基于Python实现的遥感图像的语义分割,分别使用Deeplab V3+和unet模型+源代码+文档说明+数据集.zip
- Python基于Django服装仓库进销存库存管理系统+源代码+文档说明+数据库(高分毕设)
- 2024魔改php版大屏微信墙互动展示系统 大屏幕互动系统程序动态背景图和配乐素材含搭建教程
资源上传下载、课程学习等过程中有任何疑问或建议,欢迎提出宝贵意见哦~我们会及时处理!
点击此处反馈
![feedback](https://img-home.csdnimg.cn/images/20220527035711.png)
![feedback](https://img-home.csdnimg.cn/images/20220527035711.png)
![feedback-tip](https://img-home.csdnimg.cn/images/20220527035111.png)