对于OrderedStream(int n),在初始化时创建一个长度为k+1的数组stream,用来存储后续的字符串。由于指针ptr的初始值为1,数组下标是从0开始的,所以使用长度n+1的数组可以使编码更方便。
对于String[] insert(int id, String value),直接根据题意模拟即可。将stream[id]置为value,如果stream[id]不为空,就将其加入答案,并将ptr+1,知道指针超出边界或stream[id]为空时结束并返回答案。
class OrderedStream:
def __init__(self, n: int):
self.stream = [""] * (n+1)
self.ptr = 1
def insert(self, idKey: int, value: str) -> List[str]:
self.stream[idKey] = value
ans = list()
while self.ptr < len(self.stream) and self.stream[self.ptr]:
ans.append(self.stream[self.ptr])
self.ptr += 1
return ans
# Your OrderedStream object will be instantiated and called as such:
# obj = OrderedStream(n)
# param_1 = obj.insert(idKey,value)
class OrderedStream {
private String[] stream;
private int ptr;
public OrderedStream(int n) {
stream = new String[n+1];
ptr = 1;
}
public List<String> insert(int idKey, String value) {
stream[idKey] = value;
List<String> ans = new ArrayList<String>();
while (ptr < stream.length && stream[ptr] != null) {
ans.add(stream[ptr]);
++ptr;
}
return ans;
}
}
/**
* Your OrderedStream object will be instantiated and called as such:
* OrderedStream obj = new OrderedStream(n);
* List param_1 = obj.insert(idKey,value);
*/
class OrderedStream {
private:
vector<string> stream;
int ptr;
public:
OrderedStream(int n) {
stream.resize(n+1);
ptr = 1;
}
vector<string> insert(int idKey, string value) {
stream[idKey] = value;
vector<string> ans;
while (ptr < stream.size() && !stream[ptr].empty()) {
ans.push_back(stream[ptr]);
++ptr;
}
return ans;
}
};
/**
* Your OrderedStream object will be instantiated and called as such:
* OrderedStream* obj = new OrderedStream(n);
* vector param_1 = obj->insert(idKey,value);
*/