1656.设计有序流

Posted by 云起 on 2025-02-24
Estimated Reading Time 2 Minutes
Words 448 In Total
Viewed 1 Times

1656.设计有序流

地址:1656. 设计有序流 - 力扣(LeetCode)

题目描述

n(id, value) 对,其中 id1n 之间的一个整数,value 是一个字符串。不存在 id 相同的两个 (id, value) 对。

设计一个流,以 任意 顺序获取 n(id, value) 对,并在多次调用时 id 递增的顺序 返回一些值。

实现 OrderedStream 类:

  • OrderedStream(int n) 构造一个能接收 n 个值的流,并将当前指针 ptr 设为 1

  • ```
    String[] insert(int id, String value)

    1
    2
    3
    4
    5
    6
    7



    向流中存储新的



    (id, value)

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14



    对。存储后:

    - 如果流存储有 `id = ptr``(id, value)` 对,则找出从 `id = ptr` 开始的 **最长 id 连续递增序列** ,并 **按顺序** 返回与这些 id 关联的值的列表。然后,将 `ptr` 更新为最后那个 `id + 1`
    - 否则,返回一个空列表。



    ## **示例:**

    ![img](https://assets.leetcode-cn.com/aliyun-lc-upload/uploads/2020/11/15/q1.gif)

    输入
    [“OrderedStream”, “insert”, “insert”, “insert”, “insert”, “insert”]
    [[5], [3, “ccccc”], [1, “aaaaa”], [2, “bbbbb”], [5, “eeeee”], [4, “ddddd”]]
    输出
    [null, [], [“aaaaa”], [“bbbbb”, “ccccc”], [], [“ddddd”, “eeeee”]]

解释
OrderedStream os= new OrderedStream(5);
os.insert(3, “ccccc”); // 插入 (3, “ccccc”),返回 []
os.insert(1, “aaaaa”); // 插入 (1, “aaaaa”),返回 [“aaaaa”]
os.insert(2, “bbbbb”); // 插入 (2, “bbbbb”),返回 [“bbbbb”, “ccccc”]
os.insert(5, “eeeee”); // 插入 (5, “eeeee”),返回 []
os.insert(4, “ddddd”); // 插入 (4, “ddddd”),返回 [“ddddd”, “eeeee”]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35



## 思路

暴力模拟

## 代码

```c++
class OrderedStream {
public:
vector<string> stream;
int ptr;
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;
}
};

/**
* Your OrderedStream object will be instantiated and called as such:
* OrderedStream* obj = new OrderedStream(n);
* vector<string> param_1 = obj->insert(idKey,value);
*/

复杂度

时间复杂度O(n) 空间复杂度O(n)


If you like this blog or find it useful for you, you are welcome to comment on it. You are also welcome to share this blog, so that more people can participate in it. If the images used in the blog infringe your copyright, please contact the author to delete them. Thank you !


0 comments
Anonymous
Error: Not Found.
Markdown is supported

Be the first person to leave a comment!