[LeetCode]138. Copy List with Random Pointer
来源:互联网 发布:域名 知识产权 编辑:程序博客网 时间:2024/06/06 19:33
Description:
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.
——————————————————————————————————————————————————————————————————————————Solution:
第一种方法:可以使用哈希表记录原节点和新节点一一对应的关系,以此找到random指向的节点。两次迭代。
时间复杂度:O(2n)=O(n)
空间复杂度:O(n)
/** * Definition for singly-linked list with a random pointer. * struct RandomListNode { * int label; * RandomListNode *next, *random; * RandomListNode(int x) : label(x), next(NULL), random(NULL) {} * }; */class Solution {public: RandomListNode *copyRandomList(RandomListNode *head) { if (!head) return head; map<RandomListNode*, RandomListNode*> relationship; RandomListNode *pre = new RandomListNode(-1); RandomListNode *cur = pre; RandomListNode *ptr = head; while (head) { cur->next = new RandomListNode(head->label); /* 不能在此new random节点,因为是指向list内部的节点,而不是新节点 if (head->random) cur->next->random = new RandomListNode(head->random->label); */ if (head->next) cur->next->next = new RandomListNode(head->next->label); relationship[head] = cur->next; cur = cur->next; head = head->next; } head = ptr; cur = pre->next; while (head) { if (head->random) cur->random = relationship[head->random]; head = head->next; cur = cur->next; } return pre->next; }};
第二种方法:三次迭代。第一次将每个新节点建立在每个旧节点后面;第二次将每个新节点的random指针指向旧节点random指针指向的下一个节点;第三次提取出新节点;
时间复杂度:O(3n)=O(n)
空间复杂度:O(1)
阅读全文
0 0
- LeetCode 138. Copy List with Random Pointer
- [Leetcode] 138. Copy List with Random Pointer
- LeetCode 138. Copy List with Random Pointer
- [leetcode] 138. Copy List with Random Pointer
- LeetCode 138. Copy List with Random Pointer
- LeetCode 138. Copy List with Random Pointer
- leetcode.138. Copy List with Random Pointer
- LeetCode-138.Copy List with Random Pointer
- Leetcode 138. Copy List with Random Pointer
- [Leetcode]138. Copy List with Random Pointer
- LeetCode 138. Copy List with Random Pointer
- [LeetCode] 138. Copy List with Random Pointer
- [LeetCode]138. Copy List with Random Pointer
- LeetCode 138. Copy List with Random Pointer
- Leetcode-138. Copy List with Random Pointer
- Leetcode 138. Copy List with Random Pointer
- leetcode 138. Copy List with Random Pointer
- Leetcode 138. Copy List with Random Pointer
- winsows server 2008 搭建FTP
- C++ DLL动态链接库的制作
- Linux和windows导入scv数据文件
- 初步探究ES6之箭头函数
- 哈夫曼树与哈夫曼编码
- [LeetCode]138. Copy List with Random Pointer
- HDU6200 mustedge mustedge mustedge (2017 ACM/ICPC Asia Regional Shenyang Online)
- Tensorflow实现一个完整的CNN例子
- RemoveElement
- 【C++ 模板】 如何根据模版中数据类型做对应操作?
- 如何构建物联网支付安全云
- Tomcat-高并发并设置
- 二-十进制编码即BCD编码
- hBase客户端API-增删改