LeetCode 解题思路 16(Hot 100)

解题思路:

  1. 初始化辅助节点:
  • dummy:哑节点。
  • pre:当前链表的前一个节点。
  • start:当前链表的第一个节点。
  • end:当前链表的最后一个节点。
  • nextStart:end.next,下组链表的第一个节点,用于连接当前链表尾部。
  1. 翻转当前的链表:
  • 断开当前链表与剩余链表组,end.next = null。
  • 通过 start 翻转链表并得到翻转后的头节点 newHead = reverse(start)。
  1. 连接翻转后链表:
  • 头部:pre.next = newHead;
  • 尾部:start.next = nextStart;
  1. 更新状态: pre = start。

Java代码:

java 复制代码
class Solution {
    public ListNode reverseKGroup(ListNode head, int k) {
        if (head.next == null || k == 1) return head;

        ListNode dummy = new ListNode(-1);
        dummy.next = head;
        ListNode pre = dummy;

        while (true) {
            ListNode start = pre.next;
            ListNode end = pre;
            for(int i = 0; i < k && end != null; i++){
                end = end.next;
            }
            if (end == null) break;
            ListNode nextStart = end.next;

            end.next = null;
            ListNode newHead = reverse(start);

            pre.next = newHead;
            start.next = nextStart;
            
            pre = start;
        }

        return dummy.next;
    }

    public ListNode reverse(ListNode head) {
        ListNode current = head;
        ListNode pre = null;
        while (current != null) {
            ListNode temp = current.next;
            current.next = pre;
            pre = current;
            current = temp; 
        }
        return pre;
    }
}

复杂度分析:

  • 时间复杂度: O(n)。
  • 空间复杂度: O(1),无额外空间占用。

解题思路:

  1. 第一次遍历: 创建复制节点并建立映射。
  2. 第二次遍历: 设置next和random指针。

Java代码:

java 复制代码
class Solution {
    public Node copyRandomList(Node head) {
        if (head == null) return null;
        Map<Node, Node> map = new HashMap<>();

        Node pre = head;
        while (pre != null) {
            map.put(pre, new Node(pre.val));
            pre = pre.next;
        }

        pre = head;
        while (pre != null) {
            Node copy = map.get(pre);
            copy.next = map.get(pre.next);
            copy.random = map.get(pre.random);
            pre = pre.next;
        }

        return map.get(head);
    }
}

复杂度分析:

  • 时间复杂度: O(n),需要两次遍历链表,每次遍历时间为 O(n),总时间为 O(2n) = O(n)。
  • 空间复杂度: O(n),哈希表存储所有原节点到复制节点的映射,占用 O(n) 空间。
相关推荐
好易学·数据结构2 小时前
可视化图解算法57:字符串的排列
数据结构·算法·leetcode·面试·笔试·回溯算法·牛客
এ᭄画画的北北5 小时前
力扣-283.移动零
算法·leetcode
程序员三藏6 小时前
软件测试之单元测试
自动化测试·软件测试·python·测试工具·职场和发展·单元测试·测试用例
2501_924879367 小时前
口罩识别场景误报率↓79%:陌讯多模态融合算法实战解析
人工智能·深度学习·算法·目标检测·智慧城市
Christo38 小时前
TFS-2022《A Novel Data-Driven Approach to Autonomous Fuzzy Clustering》
人工智能·算法·机器学习·支持向量机·tfs
木木子99998 小时前
超平面(Hyperplane)是什么?
算法·机器学习·支持向量机·超平面·hyperplane
是乐谷9 小时前
阿里招AI产品运营
人工智能·程序人生·面试·职场和发展·产品运营·求职招聘
星空下的曙光9 小时前
React 虚拟 DOM Diff 算法详解,Vue、Snabbdom 与 React 算法对比
vue.js·算法·react.js
♞沉寂9 小时前
数据结构——双向链表
数据结构·算法·链表
大阳1239 小时前
数据结构2.(双向链表,循环链表及内核链表)
c语言·开发语言·数据结构·学习·算法·链表·嵌入式