资讯专栏INFORMATION COLUMN

352. Data Stream as Disjoint Intervals

maybe_009 / 284人阅读

摘要:题目解答这题用会通过很快定位到当前数所处在哪两个之间,从而进行高效的比较与合并。

题目:
Given a data stream input of non-negative integers a1, a2, ..., an, ..., summarize the numbers seen so far as a list of disjoint intervals.

For example, suppose the integers from the data stream are 1, 3, 7, 2, 6, ..., then the summary will be:

[1, 1]
[1, 1], [3, 3]
[1, 1], [3, 3], [7, 7]
[1, 3], [7, 7]
[1, 3], [6, 7]

Follow up:
What if there are lots of merges and the number of disjoint intervals are small compared to the data stream"s size?

解答:
这题用Maptree会通过map.lowerKey, map.higherKey很快定位到当前数所处在哪两个interval之间,从而进行高效的比较与合并。

/**
 * Definition for an interval.
 * public class Interval {
 *     int start;
 *     int end;
 *     Interval() { start = 0; end = 0; }
 *     Interval(int s, int e) { start = s; end = e; }
 * }
 */
public class SummaryRanges {
    TreeMap map;
    /** Initialize your data structure here. */
    public SummaryRanges() {
        map = new TreeMap<>();
    }
    
    public void addNum(int val) {
        if (map.containsKey(val)) return;
        Integer l = map.lowerKey(val);
        Integer h = map.higherKey(val);
        if (l != null && h != null && map.get(l).end + 1 == val && val + 1 == map.get(h).start) {
            map.get(l).end = map.get(h).end;
            map.remove(h);
        } else if (l != null && val <= map.get(l).end + 1) {
            map.get(l).end = Math.max(map.get(l).end, val);
        } else if (h != null && map.get(h).start - 1 == val) {
            map.put(val, new Interval(val, map.get(h).end));
            map.remove(h);
        } else {
            map.put(val, new Interval(val, val));
        }
    }
    
    public List getIntervals() {
        return new ArrayList(map.values());
    }
}

/**
 * Your SummaryRanges object will be instantiated and called as such:
 * SummaryRanges obj = new SummaryRanges();
 * obj.addNum(val);
 * List param_2 = obj.getIntervals();
 */

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/65000.html

相关文章

  • 科学计算与数据可视化1

    摘要:科学计算与数据可视化程序设计模块最重要的一个特点就是其维数组对象即该对象是一个快速而灵活的大数据集容器。两行及以上为二维表示数组各维度大小的元组。 科学计算与数据可视化1 @(程序设计) numpy模块 Numpy最重要的一个特点就是其N维数组对象(即ndarray)该对象是一个快速而灵活的大数据集容器。 使用Numpy,开发人员可以执行以下操作: 1、数组的算数和逻辑运算。 2、...

    aervon 评论0 收藏0
  • TensorFlow 安装笔记

    摘要:而且我们可以看到他自动帮我们安装了,,等等需要注意的是最后会出现这里选择才能把加入环境变量中,然后才能使用不然之后就得手动配置。来安装支持的。步骤中下载太慢了,需要个小时,还是直接在线安装吧,先下载这个,然后这个只需要分钟左右。 前言 最近上了几门深度学习的公开课,还是觉得不过瘾,总觉得要搞一个框架来试试。那么caffe,tensorflow,torch等等选哪一个呢?经过一番比较我还...

    2bdenny 评论0 收藏0

发表评论

0条评论

maybe_009

|高级讲师

TA的文章

阅读更多
最新活动
阅读需要支付1元查看
<