leetcode138~Copy List with Random Pointer

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.

兩種解法,不同的是空間複雜度不同

public class CopyListwithRandomPointer {
    //時間O(n) 空間O(1)
    public RandomListNode copyRandomList(RandomListNode head) {
        if(head==null) return null;
        RandomListNode cur = head;
        //第一次遍歷,複製每個節點 放在原節點的後面
        while(cur!=null) {
            RandomListNode r = new RandomListNode(cur.label);
            r.next = cur.next;
            cur.next = r;
            cur = r.next;
        }

        cur = head;
        //第二次遍歷,添加對應的random
        while(cur!=null) {
            if(cur.random!=null) {
                cur.next.random = cur.random.next;
            }
            cur = cur.next.next;
        }

        RandomListNode nhead = head.next;
        cur = head;
        //第三次遍歷 將鏈表分離
        while(cur!=null) {
            RandomListNode tmp = cur.next;
            cur.next = tmp.next;
            if(tmp.next!=null) {
                tmp.next = tmp.next.next;
            }
            cur = cur.next;
        }
        return nhead;
    }

    //時間O(n) 空間O(n) 使用map
    public RandomListNode copyRandomList2(RandomListNode head) {
        if(head==null) return null;
        Map<RandomListNode,RandomListNode> map = new HashMap<>();
        RandomListNode node = head;
        //將新舊節點對應的存進map
        while(node!=null) {
            map.put(node, new RandomListNode(node.label));
            node = node.next;
        }
        node = head;
        for(Map.Entry<RandomListNode, RandomListNode> entry:map.entrySet()) {
            RandomListNode newNode = entry.getValue();
            newNode.next = map.get(entry.getKey().next);
            newNode.random = map.get(entry.getKey().random);
        }
        return map.get(head);
    }
}

class RandomListNode {
    int label;
    RandomListNode next,random;
    RandomListNode(int x) {
        this.label = x;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章