352. Data Stream as Disjoint Intervals
作者:互联网
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?
class SummaryRanges { // PriorityQueue<Integer> pq; List<Integer> list; /** Initialize your data structure here. */ public SummaryRanges() { // pq = new PriorityQueue<>(); list = new ArrayList(); } public void addNum(int val) { // pq.offer(val); if(list.indexOf(val) < 0) list.add(val); Collections.sort(list); // for(int i = 0; i < list.size(); i++) { // } } public int[][] getIntervals() { // System.out.println(list.toString()); List<int[]> res = new ArrayList(); for(int i = 0; i < list.size(); i++) { int cur = i; while(cur+1 < list.size() && list.get(cur+1) - list.get(cur) == 1) cur++; if(cur != i) res.add(new int[]{list.get(i), list.get(cur)}); else res.add(new int[]{list.get(i), list.get(i)}); i = cur; } int[][] result = new int[res.size()][2]; int j = 0; for(int[] tmp: res) result[j++] = tmp; return result; } } /** * Your SummaryRanges object will be instantiated and called as such: * SummaryRanges obj = new SummaryRanges(); * obj.addNum(val); * int[][] param_2 = obj.getIntervals(); */
1. first ver
Used an arraylist to store unique values, sort after every add. Then generate interval array step by step.
标签:SummaryRanges,cur,get,int,list,Intervals,Disjoint,new,Data 来源: https://www.cnblogs.com/wentiliangkaihua/p/13364150.html