LeetCode[138] 复制带随机指针的链表

个人感觉比较老的题目普遍难度都不算高,至少没有碰见答案都要看一阵才能懂的medium题目。

这题表面上看是链表,其实是hash,能想到用hash是这道题目的关键,代码如下。

class Solution {
public:
    Node* copyRandomList(Node* head) {
        Node *ptr = head;
        vector<Node *> olist;
        unordered_map<Node *, int> node;
        for (int i = 0; ptr != nullptr; ++i) {
            olist.push_back(new Node(ptr->val, nullptr, nullptr));
            node[ptr] = i;
            ptr = ptr->next;
        }
        olist.push_back(nullptr);
        ptr = head;
        for (int i = 0; ptr != nullptr; ++i) {
            olist[i]->next = olist[i+1];
            if (ptr->random != nullptr)
                olist[i]->random = olist[node[ptr->random]];
            ptr = ptr->next;
        }
        return olist[0];
    }
};

现阶段如果有提示思路的话,medium的题目基本都可以解,但是难就难在没有提示想到正确的解题思路。

猜你喜欢

转载自www.cnblogs.com/left4back/p/10463353.html