382 linked list random node (待解决)

来源:互联网 发布:打击垫 编程 编辑:程序博客网 时间:2024/04/29 22:16

382  Linked List Random Node

When I first got this question, I went through some articles, but it is painful for me to understand abstract notations like i, k, m, n, n-1, k+1...

After I read this one: http://blog.jobbole.com/42550/, it comes with a simple example and I understood suddenly, and write the code by myself. I translate it to English, so more people can benefit from it.

Start...
When we read the first node "head", if the stream "ListNode" stops here, we can just return the head.val. The possibility is 1/1.

When we read the second node, we can decide if we replace the result 'r' or not. The possibility is 1/2. So we just generate a random number between 0 and 1, and check if it is equal to 1. If it is 1, replace 'r' as the value of the current node, otherwise we don't touch 'r', so its value is still the value of head.

When we read the third node, now the result 'r' is one of value in the head or second node. We just decide if we replace 'the value of r' as 'the value of current node(third node)'. The possibility of replacing it is 1/3, namely the possibility of we don't touch r is 2/3. So we just generate a random number between 0 ~ 2, and if the result is 2 we replace 'r'.

We can continue to do like this until the end of stream "ListNode".

Here is the Java code:

public class Solution {        ListNode head;    Random random;        public Solution(ListNode head) {        this.head = head;                    }        public int getRandom() {                ListNode c = head;        int r = c.val;        for(int i=1;c.next != null;i++){                        c = c.next;            if(randInt(0,i) == i) r = c.val;                                }                return r;    }        private int randInt(int min, int max) {        return min + (int)(Math.random() * ((max - min) + 1));    }}
太傻逼了。。
1.java 生成随机数: Math.random() 生成0到1的随机数。
2.强制转换的时候没有把乘数括上...
3.这个想法还是没太懂为什么是等概率的,好喜欢这个方法,但是还要回头看
4. (int) (math.random() * num) 生成的数是在(0,num) 所以是不可能等于num的呀
如果循环从0 开始的话,那第一次生成的随机数一定是0, 则概率不等了
 
    ListNode head = 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 Solution(ListNode head) {
        this.head = head;
    }
    
    /** Returns a random node's value. */
    public int getRandom() {
        ListNode c = head;
        int result = c.val;
        for (int i = 1; c.next != null; i ++) {
            c = c.next;
            if (randi(i) == i) {
                result = c.val;
            }
        }
        return result;
    }
    
    public int randi(int num) {
        int ran = (int)(Math.random() * (num + 1));
        return ran;
    }
}
0 0