zoukankan      html  css  js  c++  java
  • 352. Data Stream as Disjoint Intervals

    /*
     * 352. Data Stream as Disjoint Intervals
     * 2016-7-12 by Mingyang
     * 这个题目做的时候一定要注意!就是我们这里讲的是点不是线段,所以点的插入就是简单多了
     * 不需要考虑同时与前面后面都发生交叉,要么在中间,要么被前面包围,要么被后面包围
     */
    class Interval {
        int start;
        int end;
        Interval() {
            start = 0;
            end = 0;
        }
        Interval(int s, int e) {
            start = s;
            end = e;
        }
    }
    class SummaryRanges {
        TreeMap<Integer, Interval> tree;
        public SummaryRanges() {
            tree = new TreeMap<>();
        }
        public void addNum(int val) {
            if (tree.containsKey(val))
                return;
            Integer l = tree.lowerKey(val);
            Integer h = tree.higherKey(val);
            if (l != null && h != null && tree.get(l).end + 1 == val && h == val + 1) {
            //首尾相连,无缝连接
                tree.get(l).end = tree.get(h).end;
                tree.remove(h);
            } else if (l != null && tree.get(l).end + 1 >= val) {
            //与前面交叉了,表明在前面的内部了
                tree.get(l).end = Math.max(tree.get(l).end, val);
            } else if (h != null && h == val + 1) {
            //刚好后面就是下一个key,被后面所吸收了
                tree.put(val, new Interval(val, tree.get(h).end));
                tree.remove(h);
            } else {
            //跟所有的不交叉,自己独立建立一个
                tree.put(val, new Interval(val, val));
            }
        }
        public List<Interval> getIntervals() {
            return new ArrayList<>(tree.values());
        }
    }
    /**
     * Your SummaryRanges object will be instantiated and called as such:
     * SummaryRanges obj = new SummaryRanges(); obj.addNum(val); List<Interval>
     * param_2 = obj.getIntervals();
     */
  • 相关阅读:
    背景透明,文字不透明
    判断数组类型
    前端工作流程自动化——Grunt/Gulp 自动化
    tools安装
    总结
    CSS Hack
    getBoundingClientRect()兼容性处理
    Math.random获得随机数
    spring RestTemplate 工程导入
    系统架构演变
  • 原文地址:https://www.cnblogs.com/zmyvszk/p/5666225.html
Copyright © 2011-2022 走看看