forked from liuyubobobo/Play-Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main2.cpp
75 lines (61 loc) · 1.77 KB
/
main2.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
64
65
66
67
68
69
70
71
72
73
74
75
/// Source : https://leetcode.com/problems/linked-list-random-node/description/
/// Author : liuyubobobo
/// Time : 2018-07-09
#include <iostream>
#include <vector>
#include <cassert>
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
///
/// This code is based on using more general reservor sampling algorithm
/// where k = 1
///
/// Time Complexity: O(n)
/// Space Complexity: O(n)
class Solution {
private:
vector<int> nums;
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) {
nums.clear();
while(head){
nums.push_back(head->val);
head = head->next;
}
}
/** Returns a random node's value. */
int getRandom() {
// In this problem, k == 1
return reservorSampling(nums, 1)[0];
}
private:
/// General Reservor Sampling Algorithm
/// From vector nums, randomly pick k elements:)
vector<int> reservorSampling(const vector<int>& nums, int k){
assert(k >= 1 && k <= nums.size());
vector<int> res(nums.begin(), nums.begin() + k);
for(int i = k ; i < nums.size() ; i ++){
int index = rand() % (i + 1);
if(index < k)
res[index] = nums[i];
}
return res;
}
};
int main() {
return 0;
}