1656.设计有序流
链接:1656.设计有序流
难度:Easy
标签:设计、数组、哈希表、数据流
简介:设计一个流,以 任意 顺序获取 n 个 (id, value) 对,并在多次调用时 按 id 递增的顺序 返回一些值。
题解 1 - rust
- 编辑时间:2022-08-16
- 执行用时:32ms
- 内存消耗:2.8MB
- 编程语言:rust
- 解法介绍:遍历。
struct OrderedStream {
    ptr: usize,
    n: usize,
    list: Vec<String>,
}
impl OrderedStream {
    fn new(n: i32) -> Self {
        let n = n as usize;
        let mut list = Vec::<String>::with_capacity(n);
        for _ in 0..n {
            list.push(String::new());
        }
        Self { ptr: 0, list, n }
    }
    fn insert(&mut self, id_key: i32, value: String) -> Vec<String> {
        self.list[(id_key - 1) as usize] = value;
        let mut ans = Vec::new();
        while self.ptr < self.n && self.list[self.ptr].len() == 5 {
            ans.push(self.list[self.ptr].clone());
            self.ptr += 1;
        }
        ans
    }
}