LeetCode探索(123):1656-设计有序流

185 阅读2分钟

携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第20天,点击查看活动详情 >>

题目

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
  • 恰好调用 ninsert

思考

本题难度简单。

首先是读懂题意。有 n(id, value) 对,其中 id1n 之间的一个整数,id 不重复,value 是一个字符串。我们需要设计一个流,以 任意 顺序获取 n(id, value) 对,并在多次调用时 id 递增的顺序 返回一些值。

根据题意,我们借助数组进行模拟。定义数组 arr 存储存入 OrderedStream 流中存入的 (id, value) 对,数组元素的索引为id,值为value。在存储新的 (id, value) 时,为 arr[id] 赋值。利用数组索引的有序性,从索引 this.ptr 开始取出,如果 arr[this.ptr] 不为空,则将该值存入返回值数组中,同时 this.ptr++。

解答

方法一:数组、模拟

/**
 * @param {number} n
 */
var OrderedStream = function(n) {
  this.arr = new Array(n).fill('')
  this.ptr = 1
}
/** 
 * @param {number} idKey 
 * @param {string} value
 * @return {string[]}
 */
OrderedStream.prototype.insert = function(idKey, value) {
  this.arr[idKey] = value
  let ans = []
  while (this.arr[this.ptr]) ans.push(this.arr[this.ptr++]) // 从this.ptr开始取出
  return ans
}

复杂度分析:

  • 时间复杂度:O(n)。
  • 空间复杂度:O(n)。

参考