leetcode 352. Data Stream as Disjoint Intervals

257 篇文章 17 订阅

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?

题目模板是:

/**
 * 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 {
	
    /** Initialize your data structure here. */
    public SummaryRanges() {

    }
    
    public void addNum(int val) {
        
    }
    
    public List<Interval> getIntervals() {
       
    }
}

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

题目意思就是:有一串正整数时间点数据,如果存在相邻的时间点,如6,7,则将它们融合成时间段,如融合成[6,7]。

我的思路就是,当一个数字 a 过来后,我要看看 a-1 的数字 之前是否存在,a+1 的数字 之前是否存在,如果存在就融合,如果不存在的话 a 就独立自成一个时间段。考虑到可以用hashmap,但是之前有个题目的解答让我得出了一个结论是:hashmap.get(i)的时间效率 小于 map[i] (map是个数组) 的时间效率,因此我们优先考虑数组。发现用数组的话,只要让map[a]=1,表示 a 这个时间点有了,然后就不用再考虑a-1或a+1了。在最后算interval时,把数组中连续的 1 合并为一个interval即可。这个方案看起来不错,问题是我们不知道数据的最大值,因此无法得知数组的大小应该为多少。我就初始假定为10000,不够再扩嘛。

public class Data_Stream_as_Disjoint_Intervals_352 {

	int[] map;
	int maxInteger;
	
	/** Initialize your data structure here. */
    public Data_Stream_as_Disjoint_Intervals_352() {
        map=new int[10000];
        maxInteger=0;
    }
    
    public void addNum(int val) {
        if(val>maxInteger){
        	maxInteger=val;
        }
        if(maxInteger>map.length+1){
        	int length=Math.max(map.length*2, maxInteger);
        	int[] newMap=new int[length+1];
        	for(int i=0;i<map.length;i++){
        		newMap[i]=map[i];
        	}
        }
        map[val]=1;
    }
    
    public List<Interval> getIntervals() {
        List<Interval> list=new ArrayList<Interval>();
        int i=0;
        int begin=0,end=0;
        while(i<=maxInteger){
        	while(map[i]==0){
        		i++;
        	}
        	begin=i;
        	while(map[i]==1){
        		i++;
        	}
        	end=i-1;
        	Interval interval=new Interval(begin,end);
        	list.add(interval);
        }
        return list;
    }

}
当然,确实有大神用了hashmap来做,找a-1和a+1,但是方法有点不太一样:map的key-value中的value 存储了以key为边界的interval的长度。某一个interval的左边界和右边界都会被存进map中。

注意:map.remove(key)不仅移除了元素,而且返回值是:以前与key指定的键名关联的键值。

    // Key -> “ left or right boundary value of range ”, Value -> " size of range "
    private Map<Integer, Integer> ranges = new HashMap<>();
    
    // Since middle val is removed, an extra set is required to de-duplicate
    private Set<Integer> dup = new HashSet<>();
    
    public void addNum(int val) {
        if (!dup.add(val)) return;
        int left = ranges.containsKey(val - 1) ? ranges.remove(val - 1) : 0;
        int right = ranges.containsKey(val + 1) ? ranges.remove(val + 1) : 0;
        int sum = left + right + 1;
        
        if (left > 0) ranges.put(val - left, sum);
        if (right > 0) ranges.put(val + right, sum);;
        //注意下面是||,因为如果left或right为0的话,val肯定是边界元素,因此要存入map
        if (left == 0 || right == 0) ranges.put(val, sum); 
    }
    
    public List<Interval> getIntervals() {
        List<Interval> ret = new ArrayList<>();
        List<Integer> keys = new ArrayList<>(ranges.keySet());
        Collections.sort(keys);
        
        int last = Integer.MIN_VALUE;
        for (int left : keys) {
            int size = ranges.get(left);
            if (left > last) {//因为同一interval的左边界和右边界都有可能在map中出现,所以要去掉重复interval
                ret.add(new Interval(left, left + size - 1));
                last = left + size - 1;
            }
        }
        return ret;
    }
还有大神用Treeset来做。
tree只包含了某个interval的开始时间点。使用 TreeMap 能够容易地找到 比val小的最大元素 和 比val大的最小元素。然后在必要时 融合时间段。
public class SummaryRanges {
    TreeMap<Integer, Interval> tree;

    public SummaryRanges() {
        tree = new TreeMap<Integer, Interval>();
    }

    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) {
            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<Interval>(tree.values());
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值