一、题目描述
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:
// Init a singly linked list [1,2,3]. ListNode head = new ListNode(1); head.next = new ListNode(2); head.next.next = new ListNode(3); Solution solution = new Solution(head); // getRandom() should return either 1, 2, or 3 randomly. Each element should have equal probability of returning. solution.getRandom();方法一:用一个vector存储链表的每个元素,然后用random随机生成一个下标。
c++代码(60ms)
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: private: vector<int> element; /** @param head The linked list's head. Note that the head is guaranteed to be not null, so it contains at least one node. */ public: Solution(ListNode* head) { while(head!=NULL){ element.push_back(head->val); head=head->next; }//while } /** Returns a random node's value. */ int getRandom() { int len=element.size(); return element[rand()%len]; } }; /** * Your Solution object will be instantiated and called as such: * Solution obj = new Solution(head); * int param_1 = obj.getRandom(); */方法二:有一个小技巧,可在遍历链表后就能马上得出结果。采用覆盖的形式,边遍历边计数已经到了第几个元素了,比如你在访问第2个元素时,count用来计数,此时count=2,如果rand()%count == 0,那么就存储当前节点的值到result中,那么命中的概率是多少呢,很显然rand()%count只能取0和1,所以概率是1/2,遍历还在继续。然后遍历第3个节点,如果第3个节点命中那么会把第3个节点的值存储到result中从而覆盖掉第2个节点的值。所以对于第2个节点,要想遍历完都不被覆盖(即选中了第2个节点)的概率这样算:1/2 * 2/3 * 3/4 * .... * (n-1)/n = 1/n。同理对于第x个节点,最后命中这个节点的概率这样算:(x-1)/x * x/(x+1) * (x+1)/(x+2) * (n-1)/n = 1/n 。所以所有的节点命中的概率都是1/n了。
c++代码(64ms)
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: private: ListNode* root; /** @param head The linked list's head. Note that the head is guaranteed to be not null, so it contains at least one node. */ public: Solution(ListNode* head) { root=head; } /** Returns a random node's value. */ int getRandom() { int result=0; ListNode *tmp=root; for(int count=1;tmp!=NULL;count++,tmp=tmp->next){ if(rand()%count==0) result=tmp->val; }//for return result; } }; /** * Your Solution object will be instantiated and called as such: * Solution obj = new Solution(head); * int param_1 = obj.getRandom(); */