PHPz2017-04-18 09:34:05
每次新建的时候验证,先查出与当前新建的有交叉的集合,然后验证集合中有没有两两交叉的,如果有,那么就会不能创建,这样就保证了不会在同一时间存在三个公告
PHP中文网2017-04-18 09:34:05
直接写个 sql 就搞定了:
select count(1) from table where start <= 新公告end and end >= 新公告start
如果结果小于3,就创建。
高洛峰2017-04-18 09:34:05
试着写了下,可以参考一下,
public class OtherTest {
public static void main(String[] args) {
boolean bn = new OtherTest().test();
System.out.println(bn);
}
public boolean test(){
//查询出在要添加的公告时间段内的公告时间段
TimeNode node1 =new TimeNode(1, 4);
TimeNode node2 =new TimeNode(1, 4);
TimeNode node3 =new TimeNode(9, 11);
List<TimeNode> list= new ArrayList<TimeNode>();
list.add(node1);
list.add(node2);
list.add(node3);
//是否有交集?
boolean insert = true;
for(int i=0;i<list.size();i++){
TimeNode nodeI = list.get(i);
for(int j=(i+1);j<list.size();j++){
TimeNode nodeJ = list.get(j);
//如果存在两个时间段有交集 那说明在交集的时间段内已经有2个公告了,不能在添加了
if(nodeI.end > nodeJ.start && nodeI.start < nodeJ.end){
insert = false; //false return
break;
}
}
if(!insert){
break;
}
}
return insert;
}
class TimeNode{
int start;
int end;
public TimeNode(int pStart,int pEnd){
start = pStart;
end = pEnd;
}
}
}
阿神2017-04-18 09:34:05
经典线段覆盖问题。不会 Java,给你个 O(n) 的思路。
先找出所有和待验证区间有交集的区间,按区间左端点从小到大排序
记第一个区间为 CurrentInternal
对于 CurrentInternal,考察其下一项 NextInterval:若不与 CurrentInternal 相交,记其为 CurrentInternal,跳至 2;否则,记其交区间为 Intersection。
对于 Intersection,遍历 NextInterval 之后的项:若无与 Intersection 相交的区间,则记 NextInterval 为 CurrentInterval,跳至 2;否则,说明有三个相交的区间,退出。
若遍历完整个列表,则证明待验证区间合法。
https://jsfiddle.net/hsfzxjy/7td0rwr2/28/