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

Linked List Random Node

2016-08-31 17:08 239 查看
题目描述:

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();

这个题最弱智的想法就是放在一个数组或list中,然后获得随机数,最后直接get即可。

leetcode并没有对内存做出检测,所以下面的做法也是可以的:

List<Integer> list=new ArrayList<Integer>();

public Solution382(ListNode head) {
while(head!=null){
list.add(head.val);
head=head.next;
}
}

/** Returns a random node's value. */
public int getRandom() {
int random=(int)(Math.random()*list.size());
return list.get(random);
}
正常的做法应该得到随机数之后,然后就直接在链表中取就行了:

public class Solution {
int size;
ListNode list;
/** @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 Solution(ListNode head) {
size = 0;
ListNode tmp = head;
list = head;
while(tmp != null) {
tmp = tmp.next;
size++;
}
}

/** Returns a random node's value. */
public int getRandom() {
if (list == null) {
return 0;
}
int rand = (int)(Math.random()*size);
ListNode tmp = list;
while(rand > 0 && tmp != null) {
tmp = tmp.next;
rand--;
}

return tmp.val;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: