# Leetcode 382. Linked List Random Node ###### tags: `Leetcode(C++)` 題目 : https://leetcode.com/problems/linked-list-random-node/ 想法 : 先把值抓出來再Ran給它。 時間複雜度 : O(n)。 程式碼 : ``` /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */ class Solution { public: vector<int> v; Solution(ListNode* head) { while(head){ v.push_back(head->val); head=head->next; } } int getRandom() { int r=rand()%v.size(); return v[r]; } }; /** * Your Solution object will be instantiated and called as such: * Solution* obj = new Solution(head); * int param_1 = obj->getRandom(); */ ```
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up