leetcode 138. Copy List with Random Pointer | 138. 复制带随机指针的链表(复杂链表的复制)
生活随笔
收集整理的這篇文章主要介紹了
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. 复制带随机指针的链表(复杂链表的复制)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: leetcode 139. Word B
- 下一篇: leetcode 140. Word B