Jan 21, 2018

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.

Follow up: What if the linked list is extremely large and its length is unknown to you? Could you solve this efficiently without using extra space?

Example:

// getRandom() should return either 1, 2, or 3 randomly. Each element should have equal probability of returning. solution.getRandom();

Solution(ListNode* p) {
len = 0;
while(p) {
len++;
p = p->next;
}
cout << len << endl;
}

/** Returns a random node's value. */
int getRandom() {
int r = rand() % len;
cout << r << endl;
while(r-- && p) {
p = p->next;
}
return p->val;
}
int len;


int getRandom() {
temp_len = 0;
return res;
}
bool getRandom(ListNode *p) {
if (p == nullptr) {
rand_n = rand() % temp_len;
return false;
}
temp_len++;
if(getRandom(p->next)) return true;
if (rand_n == 0) {
res = p->val;
return true;
}
rand_n--;
return false;
}
int temp_len;
int rand_n;
int res;


int getRandom() {
int i = 2;
while(node){
int j = rand()%i;
if(j==0)
res = node->val;
i++;
node = node->next;
}
return res;
}

LeetCodeLeetCode

Repeated-Substring-Pattern

Binary-Tree-Paths