suchen

Heim  >  Fragen und Antworten  >  Hauptteil

java - 算法问题:同一时间不能存在三个公告

1.创建公告时有生效的时间段:开始时间和过期时间;

2.当创建新的公告时,要保证同一时间点不能存在三个同时生效的公告

高洛峰高洛峰2889 Tage vor379

Antworte allen(7)Ich werde antworten

  • PHPz

    PHPz2017-04-18 09:34:05

    每次新建的时候验证,先查出与当前新建的有交叉的集合,然后验证集合中有没有两两交叉的,如果有,那么就会不能创建,这样就保证了不会在同一时间存在三个公告

    Antwort
    0
  • PHP中文网

    PHP中文网2017-04-18 09:34:05

    直接写个 sql 就搞定了:

    select count(1) from table where start <= 新公告end and end >= 新公告start

    如果结果小于3,就创建。

    Antwort
    0
  • ringa_lee

    ringa_lee2017-04-18 09:34:05

    插入时,遍历表,判断当前时间戳是否在两个时间戳之间,并记录符合该条件的数量,若>=3,不执行插入。否则,插入数据表。

    Antwort
    0
  • 阿神

    阿神2017-04-18 09:34:05

    用两个时间点,统计一下这个时间段里面有效的公告有几个!
    多余3个就不能创建了。

    Antwort
    0
  • 阿神

    阿神2017-04-18 09:34:05

    一个笨办法,查出所有时间上与新公告有交集的,然后按日做统计

    Antwort
    0
  • 高洛峰

    高洛峰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;
            }
        }
    }

    Antwort
    0
  • 阿神

    阿神2017-04-18 09:34:05

    经典线段覆盖问题。不会 Java,给你个 O(n) 的思路。

    1. 先找出所有和待验证区间有交集的区间,按区间左端点从小到大排序

    2. 记第一个区间为 CurrentInternal

    3. 对于 CurrentInternal,考察其下一项 NextInterval:若不与 CurrentInternal 相交,记其为 CurrentInternal,跳至 2;否则,记其交区间为 Intersection。

    4. 对于 Intersection,遍历 NextInterval 之后的项:若无与 Intersection 相交的区间,则记 NextInterval 为 CurrentInterval,跳至 2;否则,说明有三个相交的区间,退出。

    5. 若遍历完整个列表,则证明待验证区间合法。


    附送一个 JS 写的 DEMO,希望大家玩得开心

    https://jsfiddle.net/hsfzxjy/7td0rwr2/28/

    Antwort
    0
  • StornierenAntwort