算法系列——Copy List with Random Pointer

来源:互联网 发布:mysql修复表命令 编辑:程序博客网 时间:2024/06/13 05:57

题目描述

Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x.

You should preserve the original relative order of the nodes in each of the two partitions.

For example,
Given 1->4->3->2->5->2 and x = 3,
return 1->2->2->4->3->5.

解题思路

这个题目定义了新的数据结构,带有随机指针的链表结点,要求我们实现一这个随机链表的复制。这里我们利用哈希表来存储结点和对应生成的新节点,然后就可以通过哈希表找key对应的结点,来找到对应的random所指向的节点。空间复杂度为O(n) 时间复杂度为O(n)

程序实现

public class Solution {    public RandomListNode copyRandomList(RandomListNode head) {        if(head==null)            return null;        Map<RandomListNode,RandomListNode> map=new HashMap<RandomListNode,RandomListNode>();        RandomListNode dummyHead=new RandomListNode(-1);        RandomListNode p=dummyHead;        RandomListNode p1=head;        while(p1!=null){            RandomListNode newNode=new RandomListNode(p1.label);            map.put(p1,newNode);            p.next=newNode;            p=p.next;            p1=p1.next;        }        for(Map.Entry<RandomListNode,RandomListNode> entry:map.entrySet()){            RandomListNode key=entry.getKey();            RandomListNode value=entry.getValue();            value.random=map.get(key.random);        }        return dummyHead.next;    }}
原创粉丝点击