zoukankan      html  css  js  c++  java
  • leetcode 138. 复制带随机指针的链表

    C++采用哈希表,时间复杂度O(n),空间复杂度O(n)空间复杂度应该可以降低;

    /*
    // Definition for a Node.
    class Node {
    public:
        int val;
        Node* next;
        Node* random;
    
        Node() {}
    
        Node(int _val, Node* _next, Node* _random) {
            val = _val;
            next = _next;
            random = _random;
        }
    };
    */
    class Solution {
    public:
        Node* copyRandomList(Node* head) {
            //建立哈希表遍历两次,一次复制next并填充哈希表,第二次复制random
            unordered_map<Node*,Node*> h;
            Node *pre, *cur, *root;
            pre=root=new Node(-1,NULL,NULL);
            cur=head;
            while(cur!=NULL){
                int v=cur->val;
                Node *p=new Node(v,NULL,NULL);
                h[cur]=p;
                pre->next=p;
                pre=p;
                cur=cur->next;
            }
            cur=root->next;
            pre=head;
            h[NULL]=NULL;
            while(cur!=NULL){
                cur->random=h[pre->random];
                cur=cur->next;
                pre=pre->next;
            }
            return root->next;
        }
    };
  • 相关阅读:
    NYOJ 10 skiing DFS+DP
    51nod 1270 数组的最大代价
    HDU 4635 Strongly connected
    HDU 4612 Warm up
    POJ 3177 Redundant Paths
    HDU 1629 迷宫城堡
    uva 796
    uva 315
    POJ 3180 The Cow Prom
    POJ 1236 Network of Schools
  • 原文地址:https://www.cnblogs.com/joelwang/p/11050382.html
Copyright © 2011-2022 走看看