您的位置:首页 > Web前端 > Node.js

Linked List Random Node

2017-01-19 13:14 453 查看
题目地址:https://leetcode.com/problems/linked-list-random-node/

Given a singly linked list, return a random node’s value from the linked list. Each node must have the same probability of being chosen.

Follow up:

What if the linked list is extremely large and its length is unknown to you? Could you solve this efficiently without using extra space?

Example:

// Init a singly linked list [1,2,3]. ListNode head = new ListNode(1);

head.next = new ListNode(2); head.next.next = new ListNode(3);

Solution solution = new Solution(head);

// getRandom() should return either 1, 2, or 3 randomly. Each element

should have equal probability of returning. solution.getRandom();

代码实现:

public class LinkedListRandomNode {
public int len = 0;
public ListNode list = null;
/** @param head The linked list's head.
Note that the head is guaranteed to be not null, so it contains at least one node. */
public LinkedListRandomNode(ListNode head) {
if (head == null)
this.len = 0;

this.list = head;

ListNode p = list;
while (p != null) {
len++;
p = p.next;
}
}

/** Returns a random node's value. */
public int getRandom() {
Random r = new Random();
int rn = Math.abs(r.nextInt() % len);
System.out.println("random = " + rn);
ListNode p = list;
for (int i = 1; i <= rn; i++) {
p = p.next;
}

return p.val;
}

public static void main(String[] args) {
ListNode head = new ListNode(1);
head.next = new ListNode(2);
head.next.next = new ListNode(3);
head.next.next.next = new ListNode(4);

LinkedListRandomNode obj = new LinkedListRandomNode(head);
System.out.println(obj.getRandom());
}
}


没啥特别的,就是先遍历一遍看一下列表长度。然后生成一个长度范围内的随机数,然后再从头找到这个随机位置的节点的值就行了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  链表