【leetcode】352. Data Stream as Disjoint Intervals
题目如下:
解题思路:我的做法是val_list保存调addNum时候输入的数值,然后在调getIntervals时候将val_list中的值插入到中并返回intervalList,同时清空val_list。插入元素到intervalList时分为四种情况,一是直接插入;二是该值正好是intervalList中某个item的end+1,那么这时需要把item的end的值+1,同时检查是否和后一个item连续,如果连续则要合并;三是该值正好是intervalList中某个item的start-1,那么这时需要把item的start的值-1,这时不需要考虑和前一个item是否连续,因为在第二种情况已经做了;四是该值在某个item的(start,end)区间内,这时不做任何处理。
代码如下:
# Definition for an interval. class Interval(object): def __init__(self, s=0, e=0): self.start = s self.end = e class SummaryRanges(object): def __init__(self): """ Initialize your data structure here. """ self.intervalList = [Interval(-2, -2), Interval(pow(2, 32), pow(2, 32))] self.val_list = [] self.dic = {} def addNum(self, val): """ :type val: int :rtype: void """ if val in self.dic: return self.dic[val] = 1 import bisect bisect.insort_left(self.val_list, val) def getIntervals(self): """ :rtype: List[Interval] """ for i in self.val_list: for inx in range(len(self.intervalList)): if i > self.intervalList[inx].start and i < self.intervalList[inx].end: break elif i == self.intervalList[inx].end + 1: self.intervalList[inx].end += 1 if inx + 1 < len(self.intervalList) and self.intervalList[inx+1].start == self.intervalList[inx].end + 1: self.intervalList[inx].end = self.intervalList[inx+1].end del self.intervalList[inx+1] break elif i == self.intervalList[inx].start - 1: self.intervalList[inx].start -= 1 break elif i > self.intervalList[inx].end and i < self.intervalList[inx+1].start -1: self.intervalList.insert(inx+1,Interval(i,i)) break self.val_list = [] return self.intervalList[1:-1]