如果我有两个时间段,如何确定它们是否重叠?
可能的重复:
确定两个日期范围是否重叠
假设我有两个对象,并且每个对象对象的日期范围位于其结束日期和开始日期之间,如何以最有效或最快的方式确定两个日期范围之间是否存在重叠。
我想使用 .NET 3.5 c# 来做到这一点
Possible Duplicate:
Determine Whether Two Date Ranges Overlap
Say I have two objects, and each of these objects have a date ranges which is between its end date and start date, how do I figure out if there is any overlap between the two date ranges in the most efficient or quickest way.
I would like to do this using .NET 3.5 c#
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我不确定这是否是最有效或最快的,但这就是我要做的。如果事实证明它是瓶颈,那么只有那时我才会考虑进一步优化:
如果需要,可以通过交换范围来确保第一个范围更早(或同时)开始。
然后,如果另一个范围开始小于或等于第一个范围结束(如果范围包含开始时间和结束时间)或小于(如果范围包含开始时间且不包括结束时间),则可以检测重叠。
假设两端都包含,那么只有四种可能,其中一种是不重叠的:
范围2的端点不进入其中。因此,在伪代码中:
如果范围在开始时包含在内,在结尾处不包含,则只需在第二个 < 中将
>
替换为>=
code>if 语句:您极大地限制了必须进行的检查数量,因为您可以通过确保范围 1 永远不会在范围 2 之后开始来提前删除一半的问题空间。
Whether this is the most efficient or quickest, I'm unsure, but this is how I would do it. If it turned out to be a bottleneck, then and only then would I look into optimising further:
You ensure that the first range starts earlier (or at the same time) by swapping the ranges if necessary.
Then, you can detect overlap if the other range start is less than or equal to the first range end (if ranges are inclusive, containing both the start and end times) or less than (if ranges are inclusive of start and exclusive of end).
Assuming inclusive at both ends, there's only four possibilities of which one is a non-overlap:
The endpoint of the range 2 doesn't enter into it. So, in pseudo-code:
If the ranges are inclusive at the start and exclusive at the end, you just have to replace
>
with>=
in the secondif
statement:You greatly limit the number of checks you have to make because you remove half of the problem space early by ensuring range 1 never starts after range 2.
检查第二个对象的开始日期或结束日期是否在第一个对象的范围内:
boollap = (y.Start > x.Start && y.Start < x.End) | | (y.End > x.Start && y.End < x.End);
Check wether or not the Startdate or Enddate of the second object is in the range of the first object:
bool overlap = (y.Start > x.Start && y.Start < x.End) || (y.End > x.Start && y.End < x.End);