add: 230310

This commit is contained in:
Eatswap 2023-03-10 10:07:50 +08:00
parent 755c0c2800
commit 4969678067
Signed by: Eatswap
GPG Key ID: BE661106A1F3FA0B
2 changed files with 48 additions and 1 deletions

47
cpp/2303/230310.cpp Normal file
View File

@ -0,0 +1,47 @@
#include <cstdlib>
#include <ctime>
#include <vector>
struct ListNode {
int val;
ListNode* next;
explicit ListNode(int x = 0, ListNode* next = nullptr) : val(x), next(next) {}
};
ListNode* construct(int x) {
return new ListNode(x);
}
template<typename... Ts>
ListNode* construct(int x, Ts... xs) {
return new ListNode(x, construct(xs...));
}
/**
* 382. Linked List Random Node
* Given a singly linked list, return a random node's value from the linked list. Each node must have the same probability of being chosen.
*
* Implement the Solution class:
*
* Solution(ListNode head) Initializes the object with the head of the singly-linked list head.
* int getRandom() Chooses a node randomly from the list and returns its value. All the nodes of the list should be equally likely to be chosen.
*/
class Solution {
private:
std::vector<short> s;
public:
explicit Solution(ListNode* head) {
for (auto* ptr = head; ptr; ptr = ptr->next)
s.push_back(ptr->val);
std::srand(std::time(nullptr));
}
int getRandom() const {
int r = rand();
for (; r >= RAND_MAX / s.size() * s.size(); r = rand());
return s[r % s.size()];
}
};

View File

@ -3,4 +3,4 @@ PROJECT(2303)
SET(CMAKE_CXX_STANDARD 23) SET(CMAKE_CXX_STANDARD 23)
ADD_EXECUTABLE(2303 230303.cpp) ADD_EXECUTABLE(2303 230310.cpp)