Linked List Random Node:https://leetcode.com/problems/linked-list-random-node/
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.
这道题的核心是random,通常使用的random算法如下
#include<ctime>
#include<cstdlib>
int rd(int n){
srand((unsigned)time(NULL));
return rand()%n;
}
依据这个代码如下
class Solution{
public:
Solution(ListNode* head){
p = head;
sum = 0;
while(head){
sum++;
head = head->next;
}
}
int getRandom(){
int n = rd(sum);
ListNode* tp = p;
while(n--){
tp=tp->next;
}
return tp->val;
}
private:
ListNode* p;
int sum;
int rd(int n){
srand((unsigned)time(NULL));
return rand()%n;
}
};
但是这个代码并没有AC,它产生的所有结果是一样的!!!
查看大神代码
class Solution {
private:
ListNode* head;
public:
/** @param head The linked list's head. Note that the head is guanranteed 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* node = head->next;
int i = 2;
while(node){
int j = rand()%i;
if(j==0)
res = node->val;
i++;
node = node->next;
}
return res;
}
};
反思自己的代码发现去掉srand()便AC了!!!
class Solution{
public:
Solution(ListNode* head){
p = head;
sum = 0;
while(head){
sum++;
head = head->next;
}
}
int getRandom(){
int n = rand()%sum;
ListNode* tp = p;
while(n--){
tp=tp->next;
}
return tp->val;
}
private:
ListNode* p;
int sum;
};
我靠!!!!!