码迷,mamicode.com
首页 > 其他好文 > 详细

382. Linked List Random Node 链接列表随机节点

时间:2018-01-23 23:26:46      阅读:387      评论:0      收藏:0      [点我收藏+]

标签:return   rem   为知笔记   tee   href   line   title   space   www   

Given a singly linked list, return a random node‘s value from the linked list. Each node must have the same probability of being chosen.

Follow up:
What if the linked list is extremely large and its length is unknown to you? Could you solve this efficiently without using extra space?

Example:

// Init a singly linked list [1,2,3].
ListNode head = new ListNode(1);
head.next = new ListNode(2);
head.next.next = new ListNode(3);
Solution solution = new Solution(head);

// getRandom() should return either 1, 2, or 3 randomly. Each element should have equal probability of returning.
solution.getRandom();

  1. # Definition for singly-linked list.
  2. # class ListNode:
  3. # def __init__(self, x):
  4. # self.val = x
  5. # self.next = None
  6. import random
  7. class Solution:
  8. def __init__(self, head):
  9. """
  10. @param head The linked list‘s head.
  11. Note that the head is guaranteed to be not null, so it contains at least one node.
  12. :type head: ListNode
  13. """
  14. self.head = head
  15. self.length = 0
  16. node = head
  17. while node:
  18. self.length += 1
  19. node = node.next
  20. def getRandom(self):
  21. """
  22. Returns a random node‘s value.
  23. :rtype: int
  24. """
  25. idx = random.randint(0, self.length - 1)
  26. node = self.head
  27. while idx:
  28. idx -= 1
  29. node = node.next
  30. return node.val
  31. # Your Solution object will be instantiated and called as such:
  32. # obj = Solution(head)
  33. # param_1 = obj.getRandom()






382. Linked List Random Node 链接列表随机节点

标签:return   rem   为知笔记   tee   href   line   title   space   www   

原文地址:https://www.cnblogs.com/xiejunzhao/p/8338061.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!