题意:
给一个长度为n+1的空数组和一个初始为1的ptr,每次调用insert函数时,将value添加到下标为idKey的位置,如果ptr指向的位置非空,则返回从ptr开始的最长的非空序列,并将ptr置于之后的的第一个空位
C++代码
class OrderedStream {
protected:
vector<string> arr;
int ptr;
public:
OrderedStream(int n) : ptr(1) {
arr.resize(n + 1);
}
vector<string> insert(int idKey, string value) {
arr[idKey] = value;
vector<string> res;
while (ptr < arr.size() && !arr[ptr].empty()) {
res.emplace_back(arr[ptr ++]);
}
return res;
}
};
Java代码
class OrderedStream {
private int ptr = 1;
private String[] arr;
public OrderedStream(int n) {
arr = new String[n + 1];
}
public List<String> insert(int idKey, String value) {
List<String> res = new ArrayList<String>();
arr[idKey] = value;
while (ptr < arr.length && arr[ptr] != null)
{
res.add(arr[ptr++]);
}
return res;
}
}
/**
* Your OrderedStream object will be instantiated and called as such:
* OrderedStream obj = new OrderedStream(n);
* List<String> param_1 = obj.insert(idKey,value);
*/
3u