0
点赞
收藏
分享

微信扫一扫

把设计模式用起来!(一)——楔

Mezereon 2024-09-03 阅读 24

题目:

题解:

type Solution struct {
    head *ListNode
}

func Constructor(head *ListNode) Solution {
    return Solution{head}
}

func (s *Solution) GetRandom() (ans int) {
    for node, i := s.head, 1; node != nil; node = node.Next {
        if rand.Intn(i) == 0 { // 1/i 的概率选中(替换为答案)
            ans = node.Val
        }
        i++
    }
    return
}
举报

相关推荐

0 条评论