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 62b569a

Browse files
zhangzz2015gitbook-bot
authored andcommitted
GitBook: [greyireland#114] No subject
1 parent 888f78f commit 62b569a

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

‎suan-fa-si-wei/sampling-fang-fa.md‎

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,3 +25,37 @@ public:
2525
}
2626
};
2727
```
28+
29+
### [Linked List Random Node](https://leetcode.com/problems/linked-list-random-node/)
30+
31+
```cpp
32+
// Some code
33+
class Solution {
34+
public:
35+
36+
ListNode* head_node;
37+
Solution(ListNode* head) {
38+
head_node = head;
39+
}
40+
41+
int getRandom() {
42+
43+
ListNode* current = head_node;
44+
int result = current->val;
45+
int num =0;
46+
while(current)
47+
{
48+
num++;
49+
int randval = rand()%num;
50+
if(randval ==0 ) // 1/num to use this val.
51+
{
52+
result = current->val;
53+
}
54+
current = current->next;
55+
}
56+
57+
return result;
58+
59+
}
60+
};
61+
```

0 commit comments

Comments
(0)

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