java - 在一组范围中查找连接范围

标签 java algorithm

<分区>

假设我有以下一组范围:

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/

相关文章:

c# - 将三个文件合并为一个大文件

java - 如何重构 XSD 以便解码不返回 JAXBElement

java - 如何在 spring mvc 中的服务器端验证上显示错误消息

构造函数中泛型的 Java 类型错误

c++ - 理解这个合并排序算法?

algorithm - A*算法开表选择

algorithm - 为什么我们必须对解析树使用深度优先遍历?

c# - 从更大的 TimeSpan 中减去不同年份的 TimeSpan

java - 如何在 Spring MVC 项目中有效地使用 Scala?

java - 如何在 Spring boot 应用程序中为 HikariCP 使用 JMX MBean?