编程之美——2.19 区间重合判断

/**
 * 给定一个源区间[x, y](y >= x)和N个无序的目标区间[x1, y1], [x2, y2], ..., [xn, yn], 判断源区间[x, y]是不是在目标区间内
 * eg, 给定一个源区间[1, 6]和一组无序的目标区间[2, 3][1, 2][3, 9], 即可认为[1, 6]在区间[2, 3][1, 2][3, 9]内(因为目标区间合并之后, 实质为[1, 9])
 */


#include <stdio.h>


struct Area {
int begin;
int end;
};


void FastSort(struct Area *interval, int begin, int end) {
int i, j;
struct Area temp;
if (begin >= end)
return ;
i = begin;
j = end;
temp = interval[i];
while(i < j) {
while(i < j && temp.begin <= interval[j].begin) {
if (temp.begin == interval[j].begin) {
if (interval[j].end >= temp.end)
--j;
else
break;
} else {
--j;
}
}
interval[i] = interval[j];
while(i < j && temp.begin >= interval[i].begin) {
if (temp.begin == interval[i].begin) {
if (interval[i].end <= temp.end)
++i;
else
break;
} else {
++i;
}
}
interval[j] = interval[i];
}
interval[i] = temp;
FastSort(interval, begin, i - 1);
FastSort(interval, i + 1, end);
}


/**
 * 法一: 首先我想到的方法是将目标区间的序列中的区间合并起来, 尽可能合并所有的区间, 当剩余的区间无法合并之后, 遍历目标区间, 然后判断源区间是否在其中的某个目标区间中.
 * 首先对目标区间进行排序操作, 以x坐标为主关键字进行排序, 当x坐标相同时, 再以y坐标为关键字进行排序.
 * 当源区间在目标区间中时, 返回1; 不在返回0
 * 复杂度分析: 采用快速排序, 时间复杂度为O(N * logN), 然后遍历一次区间序列, 将可以合并的区间合并, 同时判断该区间是否包含源区间, 时间复杂度为O(N), 因此总的时间复杂度为O(N + N * logN).
 * 书中给出的解法二与我的方法类似, 首先给序列排序, 然后合并, 然后查找, 但是书中的方法是将合并与查找的过程分开了, 增加了时间复杂度.
 * 在我的算法中遍历时, 从第一个区间开始合并, 当合并到与下一个区间不相邻时, 判断合并到现在的区间是否包含目标区间:
 * 若包含, 返回1; 
 * 若未包含, 则判断目标区间是否与合并区间交叉存在(即 area.begin <= source.begin <= area.end, source.end > area.end), 若是, 返回1.
 * 若未包含且不交叉存在, 则给area赋值为序列中的下一个区间, 重新开始合并判断.
 */
int Judgement(struct Area *destination, struct Area source, int N){
struct Area area;
int i = 0;
FastSort(destination, 0, N - 1);
area.begin = destination[0].begin;
area.end = destination[0].end;
i = 1;
while(i < N) {
while(i < N && area.end >= destination[i].begin) {
if (area.end < destination[i].end)
area.end = destination[i].end;
++i;
}
if (area.begin <= source.begin && area.end >= source.end)
return 1;
if (area.begin <= source.begin && source.begin <= area.end && source.end > area.end)
return 0;
if (i < N) {
area.begin = destination[i].begin;
area.end = destination[i].end;
}
}
return 0;
}


int main() {
//struct Area destination[] = {{2, 3}, {1, 2}, {3, 9}};
//struct Area destination[] = {{2, 3}, {1, 2}, {3, 9}, {1, 2}, {3, 5}};
struct Area destination[] = {{2, 3}, {1, 2}, {4, 9}};
struct Area source = {1, 6};
printf("%d\n", sizeof(destination) / sizeof(struct Area));
if (Judgement(destination, source, sizeof(destination) / sizeof(struct Area)))
printf("源区间在目标区间中\n");
else
printf("源区间不在目标区间中\n");
return 0;
}
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值