脚本宝典收集整理的这篇文章主要介绍了

138. Copy List with Random Pointer

脚本宝典小编觉得挺不错的,现在分享给大家,也给大家做个参考,希望能帮助你少写一行代码,多一份安全和惬意。

A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null.

Return a deep copy of the list.

难度:medium

题目:给定一链表其每个结点包含一随机指针可以指向任意一结点或是为空。

思路:hash map

Runtime: 2 ms, faster than 72.52% of Java online submissions for Copy List with Random Pointer.
Memory Usage: 38.5 MB, less than 100.00% of Java online submissions for Copy List with Random Pointer.

/**
 * Definition for singly-linked list with a random pointer.
 * class RandomListNode {
 *     int label;
 *     RandomListNode next, random;
 *     RandomListNode(int x) { this.label = x; }
 * };
 */
public class Solution {
    public RandomListNode copyRandomList(RandomListNode head) {
        Map<RandomListNode, RandomListNode> mrr = new HashMap<>();
        RandomListNode ptr = head;
        while (ptr != null) {
            mrr.put(ptr, new RandomListNode(ptr.label));
            ptr = ptr.next;
        }
        ptr = head;
        while (ptr != null) {
            RandomListNode node = mrr.get(ptr);
            node.next = mrr.get(ptr.next);
            node.random = mrr.get(ptr.random);
            ptr = ptr.next;
        }
        
        return mrr.get(head);
    }
}

总结

以上是脚本宝典为你收集整理的

138. Copy List with Random Pointer

全部内容,希望文章能够帮你解决

138. Copy List with Random Pointer

所遇到的程序开发问题,欢迎加入QQ群277859234一起讨论学习。如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典网站推荐给程序员好友。 本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。

80%的人都看过