Skip to content

Commit 425e109

Browse files
Merge pull request SharingSource#313 from SharingSource/ac_oier
✨update: Modify 382
2 parents 981e864 + 6bde677 commit 425e109

File tree

1 file changed

+66
-3
lines changed

1 file changed

+66
-3
lines changed

LeetCode/381-390/382. 链表随机节点(中等).md

Lines changed: 66 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,7 @@ solution.getRandom(); // 返回 3
5050

5151
在查询时随机一个下标,并将数组中对应下标内容返回出去。
5252

53-
代码:
53+
**代码(感谢 [@Benhao](/u/himymben/) 同学提供的其他语言版本):**
5454
```Java
5555
class Solution {
5656
List<Integer> list = new ArrayList<>();
@@ -67,6 +67,36 @@ class Solution {
6767
}
6868
}
6969
```
70+
-
71+
```Python3
72+
class Solution:
73+
74+
def __init__(self, head: Optional[ListNode]):
75+
self.nodes = []
76+
while head:
77+
self.nodes.append(head)
78+
head = head.next
79+
80+
def getRandom(self) -> int:
81+
return self.nodes[randint(0, len(self.nodes) - 1)].val
82+
```
83+
-
84+
```Golang
85+
type Solution struct {
86+
Nodes []int
87+
}
88+
func Constructor(head *ListNode) Solution {
89+
nodes := make([]int, 0)
90+
for head != nil {
91+
nodes = append(nodes, head.Val)
92+
head = head.Next
93+
}
94+
return Solution{nodes}
95+
}
96+
func (this *Solution) GetRandom() int {
97+
return this.Nodes[rand.Intn(len(this.Nodes))]
98+
}
99+
```
70100
* 时间复杂度:令 $n$ 为链表长度,预处理数组的复杂度为 $O(n)$;随机获取某个值的复杂度为 $O(1)$
71101
* 空间复杂度:$O(n)$
72102

@@ -101,7 +131,7 @@ $$
101131

102132
因此,在每一次 `getRandom` 时,从前往后处理每个节点,同时记录当前节点的编号,当处理到节点 $k$ 时,在 $[0, k)$ 范围内进行随机,若随机到结果为 $0$(发生概率为 $\frac{1}{k}$),则将节点 $k$ 的值存入答案,最后一次覆盖答案的节点即为本次抽样结果。
103133

104-
代码:
134+
**代码(感谢 [@Benhao](/u/himymben/) 同学提供的其他语言版本):**
105135
```Java
106136
class Solution {
107137
ListNode head;
@@ -120,14 +150,47 @@ class Solution {
120150
}
121151
}
122152
```
153+
-
154+
```Python3
155+
class Solution:
156+
157+
def __init__(self, head: Optional[ListNode]):
158+
self.root = head
159+
160+
def getRandom(self) -> int:
161+
node, ans, i = self.root, None, 0
162+
while node:
163+
if not randint(0, i):
164+
ans = node.val
165+
node, i = node.next, i + 1
166+
return ans
167+
```
168+
-
169+
```Golang
170+
type Solution struct {
171+
Root *ListNode
172+
}
173+
func Constructor(head *ListNode) Solution {
174+
return Solution{head}
175+
}
176+
func (this *Solution) GetRandom() (ans int) {
177+
for node, idx := this.Root, 1;node != nil; idx++ {
178+
if rand.Intn(idx) == 0{
179+
ans = node.Val
180+
}
181+
node = node.Next
182+
}
183+
return
184+
}
185+
```
123186
* 时间复杂度:令 $n$ 为链表长度,随机获取某个值的复杂度为 $O(n)$
124187
* 空间复杂度:$O(1)$
125188

126189
---
127190

128191
### 最后
129192

130-
这是我们「刷穿 LeetCode」系列文章的第 `No.383` 篇,系列开始于 2021/01/01,截止于起始日 LeetCode 上共有 1916 道题目,部分是有锁题,我们将先把所有不带锁的题目刷完。
193+
这是我们「刷穿 LeetCode」系列文章的第 `No.382` 篇,系列开始于 2021/01/01,截止于起始日 LeetCode 上共有 1916 道题目,部分是有锁题,我们将先把所有不带锁的题目刷完。
131194

132195
在这个系列文章里面,除了讲解解题思路以外,还会尽可能给出最为简洁的代码。如果涉及通解还会相应的代码模板。
133196

0 commit comments

Comments
 (0)