leetcode笔记之[1656. 设计有序流]

231 阅读1分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第17天,点击查看活动详情

一、题目描述:

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

 

示例: 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 <= n <= 1000
  • 1 <= id <= n
  • value.length == 5
  • value 仅由小写字母组成
  • 每次调用 insert 都会使用一个唯一的 id
  • 恰好调用 n 次 insert

二、思路分析:

设置两个成员变量pre和strs分别存放当前指针和字符串数组

将strs数组的长度设为n + 2,无需额外处理索引从1开始以及越界的问题,进而提高执行效率

一旦指针pre位置放置了值则获取后面所有连续值,并将指针移动到null的位置(因为长度为n+2所以无需处理越界)

三、AC 代码:

class OrderedStream {
    int pre;
    String[] strs;

    public OrderedStream(int n) {
        pre = 1;
        strs = new String[n + 2];
    }
    
    public List<String> insert(int id, String value) {
        strs[id] = value;
        List<String> list = new ArrayList<>();
        if(id == pre){
            while(strs[pre] != null){
                list.add(strs[pre++]);
            }
        }
        return list;
    }
}

/**
 * Your OrderedStream object will be instantiated and called as such:
 * OrderedStream obj = new OrderedStream(n);
 * List<String> param_1 = obj.insert(id,value);
 */