题目
给你一个单链表,随机选择链表的一个节点,并返回相应的节点值。每个节点 被选中的概率一样 。
实现 Solution 类:
Solution(ListNode head) 使用整数数组初始化对象。
int getRandom() 从链表中随机选择一个节点并返回该节点的值。链表中所有节点被选中的概率相等。
示例:
输入
["Solution", "getRandom", "getRandom", "getRandom", "getRandom", "getRandom"]
[[[1, 2, 3]], [], [], [], [], []]
输出
[null, 1, 3, 2, 2, 3]
解释
Solution solution = new Solution([1, 2, 3]);
solution.getRandom(); // 返回 1
solution.getRandom(); // 返回 3
solution.getRandom(); // 返回 2
solution.getRandom(); // 返回 2
solution.getRandom(); // 返回 3
// getRandom() 方法应随机返回 1、2、3中的一个,每个元素被返回的概率相等。
提示:
链表中的节点数在范围 [1, 104] 内
-104 <= Node.val <= 104
至多调用 getRandom 方法 104 次
进阶:
如果链表非常大且长度未知,该怎么处理?
你能否在不使用额外空间的情况下解决此问题?
题解
我们可以在初始化时,用一个数组记录链表中的所有元素,这样随机选择链表的一个节点,就变成在数组中随机选择一个元素。
C
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
typedef struct {
int * arr;
int length;
} Solution;
Solution* solutionCreate(struct ListNode* head) {
Solution * obj = (Solution *)malloc(sizeof(Solution));
assert(obj != NULL);
obj->length = 0;
struct ListNode * node = head;
while (node) {
node = node->next;
obj->length++;
}
obj->arr = (int *)malloc(sizeof(int) * obj->length);
assert(obj->arr != NULL);
node = head;
for (int i = 0; i < obj->length; i++) {
obj->arr[i] = node->val;
node = node->next;
}
return obj;
}
int solutionGetRandom(Solution* obj) {
return obj->arr[rand() % obj->length];
}
void solutionFree(Solution* obj) {
free(obj->arr);
free(obj);
}
C++
class Solution {
vector<int> arr;
public:
Solution(ListNode *head) {
while (head) {
arr.emplace_back(head->val);
head = head->next;
}
}
int getRandom() {
return arr[rand() % arr.size()];
}
};
Java
class Solution {
List<Integer> list;
Random random;
public Solution(ListNode head) {
list = new ArrayList<Integer>();
while (head != null) {
list.add(head.val);
head = head.next;
}
random = new Random();
}
public int getRandom() {
return list.get(random.nextInt(list.size()));
}
}
比较一下这几种语言,有时候看着C语言的*和->还挺烦的.