把结点的值都存到一个数组中,然后每次随机生成一个下标,返回对应数组中的元素即可。
/**
* 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:
int f[10010];
int idx=0;
Solution(ListNode* head) {
while(head){
f[idx++]=head->val;
head=head->next;
}
}
int getRandom() {
return f[rand()%idx];
}
};
/**
* Your Solution object will be instantiated and called as such:
* Solution* obj = new Solution(head);
* int param_1 = obj->getRandom();
*/
时间复杂度:O(n)
空间复杂度:O(n)
本文介绍了一种通过将链表中的所有节点值存储到数组中,然后利用随机数生成器选取数组元素的方法来实现从链表中随机获取节点值。这种方法的时间复杂度为O(n),空间复杂度也为O(n)。
856

被折叠的 条评论
为什么被折叠?



