题意描述
- 给定一个单链表,返回单链表的随机结点,每一个结点的概率相同。假设链表非常大,不知道长度,不用额外的空间
- 给定一个单链表,返回单链表的随机结点,每一个结点的概率相同。假设链表非常大,不知道长度,不用额外的空间
思路1
- 首先,求出链表的长度,生成随机数,模上链表长度,再从头遍历到指定的结点(错误)
- 首先,求出链表的长度,生成随机数,模上链表长度,再从头遍历到指定的结点(错误)
思路2
代码
1234567891011121314151617181920212223242526272829303132333435363738/*** Definition for singly-linked list.* struct ListNode {* int val;* ListNode *next;* ListNode(int x) : val(x), next(NULL) {}* };*/class Solution {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) {temp = head;}/** Returns a random node's value. */int getRandom() {int res;int len = 1;ListNode* tmp = temp;while(tmp) {if(rand() % len == 0)res = tmp->val;len ++;tmp = tmp->next;}return res;}private:ListNode* temp;};/*** Your Solution object will be instantiated and called as such:* Solution obj = new Solution(head);* int param_1 = obj.getRandom();*/
第382题---Linked_list_random_node
坚持原创技术分享,您的支持将鼓励我继续创作!