欢迎访问 生活随笔!

生活随笔

当前位置: 首页 >

leetcode 138. Copy List with Random Pointer | 138. 复制带随机指针的链表(复杂链表的复制)

发布时间:2024/2/28 47 豆豆
生活随笔 收集整理的这篇文章主要介绍了 leetcode 138. Copy List with Random Pointer | 138. 复制带随机指针的链表(复杂链表的复制) 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

题目

https://leetcode.com/problems/copy-list-with-random-pointer/

题解

复杂链表的复制,经典问题,考察与 HashMap 的结合。注意如果是 map 中已经存在的(提前创建好的)节点,避免重复创建就好啦。

/* // Definition for a Node. class Node {int val;Node next;Node random;public Node(int val) {this.val = val;this.next = null;this.random = null;} } */class Solution {public Node copyRandomList(Node head) {if (head == null) return null;HashMap<Node, Node> map = new HashMap<>();map.put(null, null);Node cur = head;Node pre = new Node(-1);while (cur != null) {if (!map.containsKey(cur.random)) {map.put(cur.random, new Node(cur.random.val));}if (!map.containsKey(cur)) {map.put(cur, new Node(cur.val));}Node copy = map.get(cur);copy.random = map.get(cur.random);map.put(cur, copy);pre.next = copy;pre = copy;cur = cur.next;}return map.get(head);} }

总结

以上是生活随笔为你收集整理的leetcode 138. Copy List with Random Pointer | 138. 复制带随机指针的链表(复杂链表的复制)的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。