题目
给你一个由非负整数 a1, a2, ..., an
组成的数据流输入,请你将到目前为止看到的数字总结为不相交的区间列表。
实现 SummaryRanges
类:
SummaryRanges()
使用一个空数据流初始化对象。void addNum(int val)
向数据流中加入整数val
。int[][] getIntervals()
以不相交区间[starti, endi]
的列表形式返回对数据流中整数的总结。
示例:
输入: ["SummaryRanges", "addNum", "getIntervals", "addNum", "getIntervals", "addNum", "getIntervals", "addNum", "getIntervals", "addNum", "getIntervals"] [[], [1], [], [3], [], [7], [], [2], [], [6], []] 输出: [null, null, [[1, 1]], null, [[1, 1], [3, 3]], null, [[1, 1], [3, 3], [7, 7]], null, [[1, 3], [7, 7]], null, [[1, 3], [6, 7]]] 解释: SummaryRanges summaryRanges = new SummaryRanges(); summaryRanges.addNum(1); // arr = [1] summaryRanges.getIntervals(); // 返回 [[1, 1]] summaryRanges.addNum(3); // arr = [1, 3] summaryRanges.getIntervals(); // 返回 [[1, 1], [3, 3]] summaryRanges.addNum(7); // arr = [1, 3, 7] summaryRanges.getIntervals(); // 返回 [[1, 1], [3, 3], [7, 7]] summaryRanges.addNum(2); // arr = [1, 2, 3, 7] summaryRanges.getIntervals(); // 返回 [[1, 3], [7, 7]] summaryRanges.addNum(6); // arr = [1, 2, 3, 6, 7] summaryRanges.getIntervals(); // 返回 [[1, 3], [6, 7]]
解题
方法一:模拟
class SummaryRanges { public: vector<vector<int>> res; unordered_set<int> set; SummaryRanges() { } int binary_search(int target, int pos){ int left=0,right=res.size()-1, index; while(left<=right){ int mid=(left+right)/2; if(res[mid][pos]==target){ index=mid; break; } else if(res[mid][pos]>target){ right=mid-1; } else{ left=mid+1; } } return index; } void addNum(int val) { if(set.count(val)) return; set.insert(val); if(set.count(val+1)&&set.count(val-1)){//val-1和val+1都出现过,合并区间 int left=binary_search(val-1,1); int right=binary_search(val+1,0); res[left][1]=res[right][1]; res.erase(res.begin()+right); } else if(set.count(val+1)){//只有val+1出现过, 区间左边界变成val int index=binary_search(val+1,0); res[index][0]=val; } else if(set.count(val-1)){//只有val-1出现过,区间右边界变成val int index=binary_search(val-1,1); res[index][1]=val; } else{//val-1和val+1都没有出现过,val单独成区间 res.push_back(vector<int>{val,val}); } sort(res.begin(),res.end());//排序 } vector<vector<int>> getIntervals() { return res; } };