alec-favale-8gm2zZpvgZU-unsplash.jpg
中等给你一个单链表,随机选择链表的一个节点,并返回相应的节点值。每个节点 被选中的概率一样 。

实现 Solution 类:

Solution(ListNode head) 使用整数数组初始化对象。
int getRandom() 从链表中随机选择一个节点并返回该节点的值。链表中所有节点被选中的概率相等。
(其实我觉得并做不到选中的概率相等,因为计算机并不能生成真正的随机数)

示例:
382.链表随机节点 - 图2
输入
[“Solution”, “getRandom”, “getRandom”, “getRandom”, “getRandom”, “getRandom”]
[[[1, 2, 3]], [], [], [], [], []]
输出
[null, 1, 3, 2, 2, 3]

解释
Solution solution = new Solution([1, 2, 3]);
solution.getRandom(); // 返回 1
solution.getRandom(); // 返回 3
solution.getRandom(); // 返回 2
solution.getRandom(); // 返回 2
solution.getRandom(); // 返回 3
// getRandom() 方法应随机返回 1、2、3中的一个,每个元素被返回的概率相等。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/linked-list-random-node
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

代码

  1. var Solution = function(head) {
  2. this.list = [];
  3. this.length = 0;
  4. while (head != null) {
  5. this.list.push(head.val);
  6. this.length++;
  7. head = head.next;
  8. }
  9. };
  10. Solution.prototype.getRandom = function() {
  11. return this.list[Math.floor(Math.random() * this.length)];
  12. };