382. 链表随机节点

101 阅读1分钟

题目:
给你一个单链表,随机选择链表的一个节点,并返回相应的节点值。每个节点 被选中的概率一样

**解法: **

注意要遍历完链表,cnt从1开始。 原理:遍历长度为n的链表,每个index i被选中的概率是1/i,遍历完链表之后,则每个节点被选中的概率是1/n 证明:第i个节点被选中的概率 =11/2...(11/(i1))1/i(11/(i+1))...(11/n) = 1 * 1/2 ... (1-1/(i-1))* 1/i * (1-1/(i+1)) ...(1-1/n) =11/2...((12)/(i1))1/i(i/(i+1))...((n1)/n)=1/i = 1 * 1/2 ... ((1-2)/(i-1))* 1/i * (i/(i+1)) ...((n-1)/n) = 1/i

import "math/rand"
type Solution struct {
	List *ListNode
}


func Constructor(head *ListNode) Solution {
	return Solution{
		List: head,
	}
}


func (this *Solution) GetRandom() int {
	nodeCopy := this.List
	cnt := 1
	ans := nodeCopy.Val
	for nodeCopy != nil {
		// rand.Seed(time.Now().UnixNano())
		r := rand.Intn(cnt)
		// fmt.Println(r,cnt,time.Now().UnixNano())
		if r == 0 {
			ans = nodeCopy.Val
		}
		cnt ++
		nodeCopy = nodeCopy.Next
	}
	return ans
}