就是leetcode382
Linked List Random Node
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.
然后我写的问题如下:
但是把self.head用新变量head,s或者其他什么字母声明一下,改成:
···
cnt = 0
head = self.head
while head:
if random.randint(0, cnt) == 0:
ans = head.val
head = head.next
cnt += 1
return ans
就通过了,AC了
为什么啊? 谢谢,实在不懂, 出错的那个测试用例我也不明白,这么多中括号表示什么啊?
ringa_lee2017-04-18 09:52:12
Because the test calls getRandom multiple times on the same Solution object, you modified the object's self.head in the wrong version. After multiple calls, self.head is None, and the while loop is not executed, so an error is reported saying res is undefined. ;The modified version does not change the object head, so there is no error.
巴扎黑2017-04-18 09:52:12
The problem is that the variable res
上,getRandom()
返回的是res
,但变量res
在返回之前,只在特定条件(满足while
条件和if
条件)下才被赋值。假设你的while
循环体没有被执行,那么res
is not assigned a value before returning. The python interpreter does not know what value to return, so it reports an error.