forked from liuyubobobo/Play-Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.cpp
63 lines (49 loc) · 1.34 KB
/
main.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
/// Source : https://leetcode.com/problems/linked-list-random-node/description/
/// Author : liuyubobobo
/// Time : 2018-07-08
#include <iostream>
using namespace std;
/// Definition for singly-linked list.
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
/// Reservoir Sampling
/// The detail of Resevoir Sampling can be seen here:
/// https://www.geeksforgeeks.org/reservoir-sampling/
///
/// Attention: Don't use srand in the random problem in Leetcode
/// Since it may lead to WA
/// I think the test code use its own random seed to verify your submitted code
///
/// Time Complexity: O(n)
/// Space Complexity: O(1)
class Solution {
private:
ListNode* head;
public:
/** @param head The linked list's head.
Note that the head is guaranteed to be not null, so it contains at least one node. */
Solution(ListNode* head) {
this->head = head;
}
/** Returns a random node's value. */
int getRandom() {
int res = head->val;
ListNode* cur = head->next;
int index = 1;
// srand(time(NULL));
while(cur != NULL){
int rnd = rand() % (index + 1);
if(rnd == 0)
res = cur->val;
cur = cur->next;
index ++;
}
return res;
}
};
int main() {
return 0;
}