原题地址:https://leetcode-cn.com/problems/linked-list-random-node/submissions/
题目描述:
给定一个单链表,随机选择链表的一个节点,并返回相应的节点值。保证每个节点被选的概率一样。
进阶:
如果链表十分大且长度未知,如何解决这个问题?你能否使用常数级空间复杂度实现?
示例:
// 初始化一个单链表 [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()方法应随机返回1,2,3中的一个,保证每个元素被返回的概率相等。
solution.getRandom();
解题方案:
首先使用一个数组(顺序表)来代替链表。思路很简单,但占用了空间:
/**
* 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. */
vector<int> vec;
Solution(ListNode* head) {
ListNode* p = head;
while(p){
vec.push_back(p->val);//生成一个数组。就会比较快
p = p->next;
}
srand(NULL);
}
/** Returns a random node's value. */
int getRandom() {
if(vec.empty())
return -1;
int index = rand()%vec.size();
return vec[index];
}
};
/**
* Your Solution object will be instantiated and called as such:
* Solution obj = new Solution(head);
* int param_1 = obj.getRandom();
*/
这里再给出空间复杂度为常数级的方案:
/**
* 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. */
int length = 0;
struct ListNode* h;
Solution(ListNode* head) {
h = head;
struct ListNode* p = head;
while(p)
{
length++;
p = p->next;
}
}
/** Returns a random node's value. */
int getRandom() {
int n = random()%length;
int i;
struct ListNode* p = h;
for(i=0;i<n;i++)
p = p->next;
return p->val;
}
};
/**
* Your Solution object will be instantiated and called as such:
* Solution obj = new Solution(head);
* int param_1 = obj.getRandom();
*/