• [LeetCode]Copy List with Random Pointer &Clone Graph 复杂链表的复制&图的复制


    /**
     * 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 NULL;
            RandomListNode *p,*q;
            p=head;
            while(p){
                q=new RandomListNode(p->label);
                q->next=p->next;
                p->next=q;
                p=q->next;
            }
            p=head;
            while(p){
                q=p->next;
                if(p->random)
                    q->random=p->random->next;
                p=q->next;
            }
            p=head;
            RandomListNode*head2=p->next;
            q=head2;
            while(p){
                p->next=q->next;
                p=p->next;
                if(p){
                    q->next=p->next;
                    q=q->next;
                }
            }
            return head2;
        }
    };


    Clone Graph

     :

    类似的,对于图的复制,必须找到一种能够对新图中节点进行映射,能高速定位新节点的地址,从而使新节点指向新节点。这里採用map映射。考虑到图节点的label可能反复(本题不反复),而节点地址不反复,所以以新旧节点为键值对。

    /**
     * Definition for undirected graph.
     * struct UndirectedGraphNode {
     *     int label;
     *     vector<UndirectedGraphNode *> neighbors;
     *     UndirectedGraphNode(int x) : label(x) {};
     * };
     */
    class Solution {
    public:
        map<UndirectedGraphNode*,UndirectedGraphNode*>mp;
        map<UndirectedGraphNode*,UndirectedGraphNode*>::iterator bg;
        UndirectedGraphNode* dfs(UndirectedGraphNode*p){
            if(!p)return NULL;
            if((bg=mp.find(p))!=mp.end())
                return bg->second;
            UndirectedGraphNode *q;
            mp[p]=q=new UndirectedGraphNode(p->label);
            for(int i=0,m=p->neighbors.size();i<m;++i){
                q->neighbors.push_back(dfs(p->neighbors[i]));
            }
            return q;
        }
        UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) {
            if(!node)return NULL;
            dfs(node);
            return mp[node];
        }
    };



  • 相关阅读:
    重点---版本问题-Spark中的一次ClassNotFoundException排除
    SPARK-SQL内置函数之时间日期类
    [Spark SQL]Spark SQL读取Kudu,写入Hive
    hive和spark读取kudu表
    解决spark on yarn每次都传递一堆jars的问题
    Spark on YARN
    blocking IO, non-blocking IO, asychronous IO, sychronous IO
    使用set和vector去重(copy函数)
    vector元素去重uninque函数,erase函数
    copy与iterator头文件
  • 原文地址:https://www.cnblogs.com/mfrbuaa/p/4320940.html
Copyright © 2020-2023  润新知