<分区>
假设我有以下一组范围:
1 -> 3
4 -> 5
7 -> 8
13 -> 15
16 -> 16
我怎样才能得到一组:
1 -> 5
7 -> 8
13 -> 16
<分区>
假设我有以下一组范围:
1 -> 3
4 -> 5
7 -> 8
13 -> 15
16 -> 16
我怎样才能得到一组:
1 -> 5
7 -> 8
13 -> 16
最佳答案
为什么你需要一个图书馆?那不是那么多代码。
class Range{
int start , end;
public Range(int start , int end){
this.start = start;
this.end = end;
}
}
public static void join(List<Range> ranges){
//sort the list ascending for easier comparison
Collections.sort(ranges , (r1 , r2) -> {
if(r1 < r2)return -1;
else if(r1 > r2)return 1;
else return 0;
});
int tmp = 1; //counter for the position in the list
while(tmp < ranges.size()){
if(ranges.get(tmp).start < ranges.get(tmp - 1).end){
//the range at position tmp intersects with the previous
//one -> replace with the joined ranges
Range r = new Range(ranges.get(tmp - 1).start , ranges.get(tmp).end);
ranges.remove(tmp);
ranges.remove(tmp - 1);
ranges.add(r , tmp - 1);
}else
tmp++;//this pair (tmp - 1 / tmp) doesn't intersect -> next pair
}
}
关于java - 在一组范围中查找连接范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29564188/