【2022-08-16每日一题】1656. 设计有序流
2022-08-16
2分钟阅读时长
2022-08-16每日一题:1656. 设计有序流
- 难度:Easy
- 标签:设计 、 数组 、 哈希表 、 数据流
有 n 个 (id, value) 对,其中 id 是 1 到 n 之间的一个整数,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。
- 否则,返回一个空列表。 
 
- 如果流存储有 
示例:

输入
["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
写法一
type OrderedStream struct {
	values []string
    ptr int
}
func Constructor(n int) OrderedStream {
    return OrderedStream{
        values: make([]string, n + 1),
        ptr: 1,
    }
}
func (this *OrderedStream) Insert(idKey int, value string) (ans []string) {
	this.values[idKey] = value
    if idKey == this.ptr {
        for _, value := range this.values[idKey:] {
            if value == "" {
                break
            }
            ans = append(ans, value)
        }
        this.ptr = idKey + len(ans)
    }
    return ans
}
/**
 * Your OrderedStream object will be instantiated and called as such:
 * obj := Constructor(n);
 * param_1 := obj.Insert(idKey,value);
 */
写法二
type OrderedStream struct {
    stream []string
    ptr    int
}
func Constructor(n int) OrderedStream {
    return OrderedStream{make([]string, n+1), 1}
}
func (s *OrderedStream) Insert(idKey int, value string) []string {
    s.stream[idKey] = value
    start := s.ptr
    for s.ptr < len(s.stream) && s.stream[s.ptr] != "" {
        s.ptr++
    }
    return s.stream[start:s.ptr]
}
写法三
type OrderedStream struct {
    arr []string 
    p int
}
func Constructor(n int) OrderedStream {
    return OrderedStream{
        arr: make([]string, n+1),
        p: 1,
    }
}
func (this *OrderedStream) Insert(idKey int, value string) (ans []string) {
    this.arr[idKey] = value
    if idKey == this.p {
        for ; idKey != len(this.arr) && this.arr[idKey] != "";idKey++{
            ans = append(ans, this.arr[idKey])
        }
        this.p = idKey
    }
    return ans
}