LeetCode—382. Linked List Random Node

Linked List Random Node思路:常数空间求随机元素,显然不能用队列存储,那么利用公式

第i个元素取到的概率等于 1/i,他被保留的概率等于  1/i*(i/(1+i))*.......*(n-1/n)=1/n


GitHub地址https://github.com/corpsepiges/leetcode

目前java版本的答案大约进度是免费的差40题,python大约是一半,其他的等以后再补充。

点此进入如果可以的话,请点一下star,谢谢。



/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    ListNode node;
    /** @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) {
        node=head;
    }
    
    /** Returns a random node's value. */
    public int getRandom() {
        ListNode ans=node;
        int val=ans.val;
        Random r=new Random();
        for (int i = 1; ans!=null; i++) {
            if (r.nextInt(i)==0) {
                val=ans.val;
            }
            ans=ans.next;
        }
        return val;
    }
}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值