很抱歉,您没有提供需要改写的句子。请提供您希望改写的句子,我将为您改写为一个长尾词的。
- 内容介绍
- 文章标签
- 相关推荐
本文共计483个文字,预计阅读时间需要2分钟。
题目:给你一个单链表,随机选择链表中的一个节点,并返回相应节点的值。每个节点被选中的概率一样。
实现 Solution 类:Solution(ListNode head) 使用整数数组初始化对象。int getRandom() 返回随机选中的节点的值。
pythonimport random
class ListNode: def __init__(self, val=0, next=None): self.val=val self.next=next
class Solution: def __init__(self, head: ListNode): self.head=head
def getRandom(self) -> int: current=self.head result=0 count=0
while current: count +=1 # 随机选择一个数,如果等于1,则选择当前节点的值 if random.randint(1, count)==1: result=current.val current=current.next
return result
题目:
给你一个单链表,随机选择链表的一个节点,并返回相应的节点值。每个节点 被选中的概率一样 。
实现 Solution 类:
Solution(ListNode head) 使用整数数组初始化对象。
int getRandom() 从链表中随机选择一个节点并返回该节点的值。链表中所有节点被选中的概率相等。
示例:
输入
["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中的一个,每个元素被返回的概率相等。
代码实现:
class Solution {List<Integer> list;
Random random;
public Solution(ListNode head) {
list = new ArrayList<Integer>();
while (head != null) {
list.add(head.val);
head = head.next;
}
random = new Random();
}
public int getRandom() {
return list.get(random.nextInt(list.size()));
}
}
本文共计483个文字,预计阅读时间需要2分钟。
题目:给你一个单链表,随机选择链表中的一个节点,并返回相应节点的值。每个节点被选中的概率一样。
实现 Solution 类:Solution(ListNode head) 使用整数数组初始化对象。int getRandom() 返回随机选中的节点的值。
pythonimport random
class ListNode: def __init__(self, val=0, next=None): self.val=val self.next=next
class Solution: def __init__(self, head: ListNode): self.head=head
def getRandom(self) -> int: current=self.head result=0 count=0
while current: count +=1 # 随机选择一个数,如果等于1,则选择当前节点的值 if random.randint(1, count)==1: result=current.val current=current.next
return result
题目:
给你一个单链表,随机选择链表的一个节点,并返回相应的节点值。每个节点 被选中的概率一样 。
实现 Solution 类:
Solution(ListNode head) 使用整数数组初始化对象。
int getRandom() 从链表中随机选择一个节点并返回该节点的值。链表中所有节点被选中的概率相等。
示例:
输入
["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中的一个,每个元素被返回的概率相等。
代码实现:
class Solution {List<Integer> list;
Random random;
public Solution(ListNode head) {
list = new ArrayList<Integer>();
while (head != null) {
list.add(head.val);
head = head.next;
}
random = new Random();
}
public int getRandom() {
return list.get(random.nextInt(list.size()));
}
}

