标签:
public class Solution { public RandomListNode copyRandomList(RandomListNode head) { //http://www.cnblogs.com/springfor/p/3864457.html if(head==null) return null; //soln 1 HashMap 遍历2次list,所以时间复杂度是O(2n)=O(n),然后使用了HashMap,所以空间复杂度是O(n)。 RandomListNode newhd = new RandomListNode(head.label); RandomListNode oldhd = head; RandomListNode oldp = head.next; RandomListNode newp = newhd; HashMap<RandomListNode, RandomListNode> hm = new HashMap<RandomListNode, RandomListNode>(); hm.put(oldhd, newhd); //Map<K,V> , which is key,which is value? while(oldp!=null){ RandomListNode newnode = new RandomListNode(oldp.label); newp.next = newnode; newp = newp.next; hm.put(oldp,newp); oldp = oldp.next; } oldp = head; newp = newhd; while(oldp!=null){ newp.random = hm.get(oldp.random); newp = newp.next; oldp = oldp.next; } return newhd; //soln 2 a) replica old nodes twice, b) replica node.next(which is node‘s replica).random = node.random.next(which is random‘s replica) , c) separate node and its replica RandomListNode node = head; while(node!=null){ RandomListNode newnode = new RandomListNode(node.label); newnode.next = node.next; node.next = newnode; // a) replica old nodes twice node =newnode.next; } node = head; while(node!=null){ if(node.random!=null) node.next.random = node.random.next; // b) replica node.next(which is node‘s replica).random = node.random.next(which is random‘s replica) node = node.next.next; } node = head; RandomListNode newhd = head.next; while(node!=null){ RandomListNode rep = node.next; node.next = rep.next; if(rep.next!=null) rep.next = rep.next.next; node = node.next; } return newhd; } }
标签:
原文地址:http://www.cnblogs.com/jiajiaxingxing/p/4407427.html