如何检查多个数字范围重叠的错误

时间:2017-09-12 05:54:53

标签: javascript arrays

我在javascript中遇到问题,我需要确定数字范围的集合是否重叠。 例子:

1 - 5, 4 - 6, 7 - 8 (有重叠)

1 - 5, 6 - 8, 9 - 12 (没有重叠)

提前感谢!

1 个答案:

答案 0 :(得分:1)

必须首先对范围集进行排序,以便起始元素始终大于(不小于)先前的起始编号。在您的情况下,它将被排序。 然后,对于每个范围,检查起始编号是否大于上一个结束编号。如果对于所有范围都是如此,则其不重叠。

var ranges=[[1,5],[4,6],[7,8]];
ranges.sort() // sorting is done with respect to the first element in the array. 
for(var i=1;i<ranges.length;i++){ //start with the second element and compare it with the first
    if(ranges[i][0]<=ranges[i-1][1])
        break; 
}
if(i==ranges.length)
    console.log("Non overlapping")
else
    console.log("overlapping")