设计有序流(design-an-ordered-stream)
设计有序流(design-an-ordered-stream)
package weekly_contest_215;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
//5601. 设计有序流(design-an-ordered-stream)
public class OrderedStream {
private int len;
private int ptr;
private String[] str;
public OrderedStream(int n) {
str = new String[n];
ptr = 1;
len = n;
}
public List<String> insert(int id, String value) {
int index = id - 1;
str[index] = value;
List<String> list = new ArrayList<>();
if (id == ptr) {
while (index<len && str[index]!=null) {
list.add(str[index]);
index++;
}
ptr = index + 1;
return list;
}
return Collections.EMPTY_LIST;
}
public static void main(String[] args) {
OrderedStream os= new OrderedStream(5);
System.out.println(os.insert(3, "ccccc")); // 插入 (3, "ccccc"),返回 []
System.out.println(os.insert(1, "aaaaa")); // 插入 (1, "aaaaa"),返回 ["aaaaa"]
System.out.println(os.insert(2, "bbbbb")); // 插入 (2, "bbbbb"),返回 ["bbbbb", "ccccc"]
System.out.println(os.insert(5, "eeeee")); // 插入 (5, "eeeee"),返回 []
System.out.println(os.insert(4, "ddddd")); // 插入 (4, "ddddd"),返回 ["ddddd", "eeeee"]
}
}
/**
* Your OrderedStream object will be instantiated and called as such:
* OrderedStream obj = new OrderedStream(n);
* List<String> param_1 = obj.insert(id,value);
*/
// ["OrderedStream", "insert", "insert", "insert", "insert", "insert"]
// [[5], [3, "ccccc"], [1, "aaaaa"], [2, "bbbbb"], [5, "eeeee"], [4, "ddddd"]]