class Solution {
private:
ListNode *head;
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) {
srand(time(NULL));
this->head=head;
}
int random(double min,double max)
{
return (int)(min+((max-min+1)*rand()/(RAND_MAX)));
}
/** Returns a random node's value. */
int getRandom() {
int r=head->val;
ListNode *c=head->next;
for(int i=1;c!=NULL;i++)
{
if(random(0,i)==i)r=c->val;
c=c->next;
}
return r;
}
};
382. Linked List Random Node
最新推荐文章于 2018-11-27 21:33:50 发布