382
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
Random random=new Random();
List<Integer>list=new ArrayList<>();
public Solution(ListNode head) {
while(head!=null){
list.add(head.val);
head=head.next;
}
}
public int getRandom() {
return list.get(random.nextInt(list.size()));
}
}
/**
* Your Solution object will be instantiated and called as such:
* Solution obj = new Solution(head);
* int param_1 = obj.getRandom();
*/
138
代码
/*
// Definition for a Node.
class Node {
int val;
Node next;
Node random;
public Node(int val) {
this.val = val;
this.next = null;
this.random = null;
}
}
*/
class Solution {
/**递归结合哈希表 */
Map<Node,Node>map=new HashMap<>();
public Node copyRandomList(Node head) {
if(head==null){
return null;
}
if(!map.containsKey(head)){
Node newNode=new Node(head.val);
map.put(head,newNode);
newNode.next=copyRandomList(head.next);
newNode.random=copyRandomList(head.random);
}
return map.get(head);
}
}