题目:
给你一个单链表,随机选择链表的一个节点,并返回相应的节点值。每个节点 被选中的概率一样
**解法: **
注意要遍历完链表,cnt从1开始。 原理:遍历长度为n的链表,每个index i被选中的概率是1/i,遍历完链表之后,则每个节点被选中的概率是1/n 证明:第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
}