zoukankan      html  css  js  c++  java
  • LeetCode "Copy List with Random Pointer"

    Two passes: all pointer linking info will be recorded in 1st pass - to hashmap; 2nd pass recover the pointer relationship from hashmap. 1A! 

    class Solution {
    public:
        RandomListNode *copyRandomList(RandomListNode *head) {
            if (!head) return NULL;
    
            vector<RandomListNode *> vec;
            unordered_map<RandomListNode *, unsigned> ptrMap;
            //    1st pass
            RandomListNode *p = head;
            unsigned i = 0;
            while (p)
            {
                RandomListNode *pCurr = new RandomListNode(p->label);
                pCurr->random = p->random;
                pCurr->next = p->next;
                vec.push_back(pCurr);
                ptrMap.insert(make_pair(p, i ++));
                p = p->next; 
            }
            //    2nd pass
            for (int i = 0; i < vec.size(); i++)
            {
                RandomListNode *pCurr = vec[i];
                if (pCurr->next)    pCurr->next = vec[ptrMap[pCurr->next]];
                if (pCurr->random)    pCurr->random = vec[ptrMap[pCurr->random]];
            }
            return vec[0];
        }
    };
  • 相关阅读:

    入门动态规划问题
    AC自动机
    KMP算法
    [OpenGL]用鼠标拖拽图形移动
    HDU-2222 Keywords Search
    Trie
    Manacher算法
    linux环境搭建
    Android Studio使用JNI和NDK进行开发
  • 原文地址:https://www.cnblogs.com/tonix/p/3862735.html
Copyright © 2011-2022 走看看