内容简介: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
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);
}
}
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网
猜你喜欢:本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Effective Modern C++ 简体中文版
Scott Meyers / 高博 / 中国电力出版社 / 2018-4-23 / 99
想要彻底理解C++11和C++14,不可止步于熟悉它们引入的语言特性(例如,auto型别推导、移动语义、lambda表达式以及并发支持)。挑战在于高效地运用这些特性——从而使你的软件具备正确性、高效率、可维护性和可移植性。这正是这本实用的图书意欲达成的定位。它描述的正是使用C++11和C++14——现代C++来撰写真正卓越的软件之道。 涵盖以下主题: 大括号初始化、noexcept规格......一起来看看 《Effective Modern C++ 简体中文版》 这本书的介绍吧!