码迷,mamicode.com
首页 > 其他好文 > 详细

352. Data Stream as Disjoint Intervals

时间:2016-07-13 11:41:04      阅读:159      评论:0      收藏:0      [点我收藏+]

标签:

/*
 * 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();
 */

 

352. Data Stream as Disjoint Intervals

标签:

原文地址:http://www.cnblogs.com/zmyvszk/p/5666225.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!