class OrderedStream {
public:
OrderedStream(int n) {
stream.resize(n + 1);
ptr = 1;
}
vector<string> insert(int idKey, string value) {
stream[idKey] = value;
vector<string> res;
while (ptr < stream.size() && !stream[ptr].empty()) {
res.push_back(stream[ptr]);
++ptr;
}
return res;
}
private:
vector<string> stream;
int ptr;
};
使用数组存储 + 遍历、
我们在初始化时开辟一个长度为 n+1 的数组 stream,用来存储后续的字符串。注意到题目中指针 ptr 的初始值为 1,而多数语言数组的下标是从 0 开始的,因此使用长度为 n+1 的数组可以使得编码更加容易。