• ​力扣解法汇总1656-设计有序流


     目录链接:

    力扣编程题-解法汇总_分享+记录-CSDN博客

    GitHub同步刷题项目:

    GitHub - September26/java-algorithms: 算法题汇总,包含牛客,leetCode,lintCode等网站题目的解法和代码,以及完整的mode类,甚至链表代码生成工具都有提供。

    原题链接:力扣


    描述:

    有 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


    来源:力扣(LeetCode)
    链接:https://leetcode.cn/problems/design-an-ordered-stream
    著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

    解题思路:

    * 解题思路:
    * 设置一个数组用来存放(id,value),以及一个ptr来记录位置。
    * 每次插入的时候,先设置对应位置的数据,然后从ptr开始遍历,如果为空就跳出循环,ptr=i;
    * 否则加入到集合中返回。
    * 由于本题中是从1开始的,所以数组长度设置为n+1,0的位置不使用。

    代码:

    1. public class Solution1656 {
    2. public static class OrderedStream {
    3. int ptr = 1;
    4. String[] strings;
    5. public OrderedStream(int n) {
    6. strings = new String[n + 1];
    7. }
    8. public List<String> insert(int idKey, String value) {
    9. strings[idKey] = value;
    10. ArrayList<String> list = new ArrayList<>();
    11. if (this.strings[ptr] == null) {
    12. return list;
    13. }
    14. for (int i = ptr; i < strings.length; i++) {
    15. if (strings[i] == null) {
    16. ptr = i;
    17. break;
    18. }
    19. list.add(strings[i]);
    20. }
    21. return list;
    22. }
    23. }
    24. }

  • 相关阅读:
    centos7.9 扩容swap分区
    Linux下yum源配置实战
    读书感悟【Vue.js设计与实现】第1章 权衡的艺术 【Vue进阶系列】
    部门树递归实现
    MySQL---DML+DQL+DCL
    jQuery学习:事件处理(绑定事件 解绑事件 事件委派/委托))
    linux系统编程
    git配置SSH 公钥
    mac系统如何安装nacos(window系统通用)?详细教程一文解决
    2022.8.25-----leetcode.658
  • 原文地址:https://blog.csdn.net/AA5279AA/article/details/126361391