本题源自leetcode 382;
-------------------------------------------------------------
思考:用一个随机函数,来做选择。
代码:
ListNode* head;
/** @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* root = head->next;
int i = 2;
while(root){
int j = rand() % i;
if(j == 0)
res = root->val;
root = root->next;
i++;
}
return res;
}

本文介绍了一种解决LeetCode上第382题的方法,该题要求从给定的链表中随机返回一个节点的值。通过遍历链表并使用随机数生成器来实现这一目标。

944

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



