假设我有以下一系列范围:
1 -> 3
4 -> 5
7 -> 8
13 -> 15
16 -> 16
我如何得到一套:
1 -> 5
7 -> 8
13 -> 16
答案 0 :(得分:0)
为什么你需要一个库?那不是那么多代码。
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
}
}
答案 1 :(得分:0)
我可能会使用套装。 (psudo-code)类似
pairs = "a -> b \n c -> d \n e -> f"
例如
listOfPairs = pairs.split("\n")
_set = new set()
for k : listOfPairs{
temp = k.split("->")
_set += _set( range(temp[1],temp[2]) )
}
此时我们有一个包含范围内所有数字的集合。现在我们必须超越总范围并确定子范围。
c = min(_set)
ans = ""
while(c <= max(_set)){
if(c in _set && !(c-1 in _set) ){
ans += string(c) + "->"
}
if( (c in _set) && !(c+1 in _set) ){
ans += string(c) + " \n"
}
}
答案 2 :(得分:0)
这也可以使用TreeMap实现,其中键的范围是开始,值是范围结束,如下所示:
public class ContinuousRangeSet {
private TreeMap<Integer, Integer> ranges = new TreeMap<Integer, Integer>();
public void addRange(int start, int end) {
int effectiveStart = start, effectiveEnd = end;
Map.Entry<Integer, Integer> previousRange = ranges.floorEntry(start);
if (previousRange != null && previousRange.getValue() + 1 >= start) {
// the start is in the middle of an existing range
effectiveStart = previousRange.getKey();
}
SortedMap<Integer,Integer> overlappingRanges = ranges.subMap(start, true, end + 1, true);
if (!overlappingRanges.isEmpty()) {
Integer lastOverlappingKey = overlappingRanges.lastKey();
if (ranges.get(lastOverlappingKey) > end) {
// the end is in the middle of an existing range
effectiveEnd = ranges.get(lastOverlappingKey);
}
}
// we don't want to keep the overlapping ranges
overlappingRanges.clear();
ranges.put(effectiveStart, effectiveEnd);
}
public static void main(String[] args) {
ContinuousRangeSet rangeSet = new ContinuousRangeSet();
rangeSet.addRange(1, 3);
rangeSet.addRange(4, 5);
rangeSet.addRange(7, 8);
rangeSet.addRange(13, 15);
rangeSet.addRange(16, 16);
System.out.println(rangeSet.ranges);
rangeSet.addRange(3, 14);
System.out.println(rangeSet.ranges);
}
}
输出:
{1=5, 7=8, 13=16}
{1=16}
(注意我没有测试所有边缘情况......)