# 间隔问题 [No. 56]

1147人阅读 评论(0)

/*
* s1: start point of interval 1
* e1: end point of interval 1
* s2: start point of interval 2
* e2: end point of interval 2
*/
public boolean overlap(int s1, int e1, int s2, int e2) {
return Math.max(s1, s2) < Math.min(e1, e2);
}

public class Test {
//check whether the two intervals intersect
public boolean overlap(Interval i1, Interval i2) {
return Math.max(i1.start, i2.start) < Math.min(i1.end, i2.end);
}

//add the new interval to the interval list and return a new interval list without overlapping
public ArrayList<Interval> add(ArrayList<Interval> list, Interval interval) {
ArrayList<Interval> newList = new ArrayList<Interval>();
int i = 0;
while (i < list.size()) {
//no intersection
if (overlap(list.get(i), interval) == false) {
i++;
} else {
//get the new interval
while (i < list.size() && overlap(list.get(i), interval) == true) {
int start = Math.min(list.get(i).start, interval.start);
int end = Math.max(list.get(i).end, interval.end);
interval = new Interval(start, end);
i++;
}
}
}
return newList;
}

public static void main(String[] args) {
ArrayList<Interval> list = new ArrayList<Interval>();

Collections.sort(list);
Interval interval = new Interval(40, 48);

Test test = new Test();
for(Interval inter : newList) {
System.out.println("[" + inter.start + ", " + inter.end + "]");
}
}
}

class Interval implements Comparable<Interval>{
int start;
int end;

Interval(int start, int end) {
this.start = start;
this.end = end;
}

public int compareTo(Interval o) {
if (start > ((Interval)o).start ||
(start == ((Interval)o).start && end > ((Interval)o).end)) {
return 1;
} else if (start == ((Interval)o).start && end == ((Interval)o).end) {
return 0;
}
return -1;
}
}

0
1

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：600016次
• 积分：6373
• 等级：
• 排名：第3841名
• 原创：122篇
• 转载：21篇
• 译文：0篇
• 评论：172条
文章分类
评论排行
最新评论