Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit c4f58c2

Browse files
✨update: Modify 382
1 parent f47e858 commit c4f58c2

File tree

1 file changed

+65
-2
lines changed

1 file changed

+65
-2
lines changed

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

Lines changed: 65 additions & 2 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,6 +150,39 @@ 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

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /