C++ 中将数据流表示为不相交区间
假设我们有一个整数数据流输入,例如 a1, a2, ..., an, ..., 我们必须将到目前为止看到的数字总结为不相交区间的列表。例如,假设输入整数为 1, 3, 8, 2, 7, ..., 则摘要将为:
[1,1]
[1, 1], [3, 3]
[1, 1], [3, 3], [8, 8]
[1, 3], [8, 8]
[1, 3], [7, 8].
为了解决这个问题,我们将遵循以下步骤:
创建一个名为 nums 的集合
在初始化器中,设置 low := -inf 和 high := inf
在接收 num 作为输入的 addNum 方法中,将 num 插入到集合 nums 中
在 get interval 方法中,执行以下操作:
定义一个二维数组 ret
it := 集合 nums 的起始元素
当 it 在集合中时,执行:
x := it 的值
如果 ret 为空或 ret 的最后一个元素的索引 1 的元素 + 1 < x,则:
在 ret 的末尾插入对 {x, x}
否则
将 ret 的最后一个元素的索引 1 的元素加 1
it 指向下一个元素
返回 ret
示例
让我们看看下面的实现,以便更好地理解:
#include <bits/stdc++.h<
using namespace std;
void print_vector(vector<vector<auto> > v){
cout << "[";
for(int i = 0; i<v.size(); i++){
cout << "[";
for(int j = 0; j <v[i].size(); j++){
cout << v[i][j] << ", ";
}
cout << "],";
}
cout << "]"<<endl;
}
class SummaryRanges {
public:
set <int> nums;
int low, high;
SummaryRanges() {
low = INT_MAX;
high = INT_MIN;
}
void addNum(int val) {
nums.insert(val);
}
vector<vector<int>> getIntervals() {
vector < vector <int> > ret;
set <int> :: iterator it = nums.begin();
while(it != nums.end()){
int x = *it;
if(ret.empty() || ret.back()[1] + 1 < x){
ret.push_back({x, x});
} else {
ret.back()[1]++;
}
it++;
}
return ret;
}
};
main(){
SummaryRanges ob;
ob.addNum(1);
print_vector(ob.getIntervals());
ob.addNum(3);
print_vector(ob.getIntervals());
ob.addNum(8);
print_vector(ob.getIntervals());
ob.addNum(2);
print_vector(ob.getIntervals());
ob.addNum(7);
print_vector(ob.getIntervals());
}输入
Initialize the class, then insert one element at a time and see the intervals. So the elements are [1,3,8,2,7]
输出
[[1, 1, ],] [[1, 1, ],[3, 3, ],] [[1, 1, ],[3, 3, ],[8, 8, ],] [[1, 3, ],[8, 8, ],] [[1, 3, ],[7, 8, ],]
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP