352. 将数据流变为多个不相交区间
生活随笔
收集整理的這篇文章主要介紹了
352. 将数据流变为多个不相交区间
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
352. 將數(shù)據(jù)流變?yōu)槎鄠€(gè)不相交區(qū)間
給你一個(gè)由非負(fù)整數(shù) a1, a2, …, an 組成的數(shù)據(jù)流輸入,請(qǐng)你將到目前為止看到的數(shù)字總結(jié)為不相交的區(qū)間列表。
實(shí)現(xiàn) SummaryRanges 類:
- SummaryRanges() 使用一個(gè)空數(shù)據(jù)流初始化對(duì)象。
- void addNum(int val) 向數(shù)據(jù)流中加入整數(shù) val 。
- int[][] getIntervals() 以不相交區(qū)間 [starti, endi] 的列表形式返回對(duì)數(shù)據(jù)流中整數(shù)的總結(jié)。
解題思路
使用優(yōu)先隊(duì)列維護(hù)有序的數(shù)據(jù)流,當(dāng)需要獲得不相交的區(qū)間時(shí),我們可以遍歷優(yōu)先隊(duì)列,判斷有序的數(shù)據(jù)流可以組成的不相交區(qū)間
代碼
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();*/總結(jié)
以上是生活随笔為你收集整理的352. 将数据流变为多个不相交区间的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 怀孕的人梦到鱼是什么征兆
- 下一篇: 441. 排列硬币