本文主要是介绍Golang | Leetcode Golang题解之第382题链表随机节点,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
题目:
题解:
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
}
这篇关于Golang | Leetcode Golang题解之第382题链表随机节点的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!