352. 将数据流变为多个不相交区间
生活随笔
收集整理的這篇文章主要介紹了
352. 将数据流变为多个不相交区间
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
352. 將數據流變為多個不相交區間
給你一個由非負整數 a1, a2, …, an 組成的數據流輸入,請你將到目前為止看到的數字總結為不相交的區間列表。
實現 SummaryRanges 類:
- SummaryRanges() 使用一個空數據流初始化對象。
- void addNum(int val) 向數據流中加入整數 val 。
- int[][] getIntervals() 以不相交區間 [starti, endi] 的列表形式返回對數據流中整數的總結。
解題思路
使用優先隊列維護有序的數據流,當需要獲得不相交的區間時,我們可以遍歷優先隊列,判斷有序的數據流可以組成的不相交區間
代碼
class SummaryRanges {PriorityQueue<Integer> pq = new PriorityQueue<>();public SummaryRanges() {}public void addNum(int val) {pq.add(val);}public int[][] getIntervals() {int pre = pq.poll(), s = pre;List<int[]> list = new ArrayList<>();while (!pq.isEmpty()) {Integer cur = pq.poll();if (cur==pre) continue;if (cur == pre + 1) {pre++;} else {list.add(new int[]{s,pre});s=pre=cur;}}list.add(new int[]{s,pre});int j=0;int[][] res=new int[list.size()][2];for (int[] ints : list) {for (int i=ints[0];i<=ints[1];i++)pq.add(i);res[j++]=ints;}return res;}}/*** Your SummaryRanges object will be instantiated and called as such:* SummaryRanges obj = new SummaryRanges();* obj.addNum(val);* int[][] param_2 = obj.getIntervals();*/總結
以上是生活随笔為你收集整理的352. 将数据流变为多个不相交区间的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 怀孕的人梦到鱼是什么征兆
- 下一篇: 梦到没考上大学是什么意思