
给出一个链表,随机返回链表中的一个数字,平均分布。
思路:
- 把链表的数字保存到一个数组里面,然后随机取数组下标,得到数字
class Solution {
Random random = new Random();
List<Integer> arr = new ArrayList<>();
public Solution(ListNode head) {
while(head != null) {
arr.add(head.val);
head = head.next;
}
}
public int getRandom() {
int idx = random.nextInt(arr.size());
return arr.get(idx);
}
}
- 构造函数中遍历链表元素得到长度len, getRandom函数中从0~len中随机取下标,得到下标之后遍历链表到下标处,得到数字。
测试此方法耗时更短
class Solution {
ListNode headNode;
int len = 0;
Random random = new Random();
public Solution(ListNode head) {
this.headNode = head;
while(head != null) {
len ++;
head = head.next;
}
}
public int getRandom() {
int idx = random.nextInt(len);
ListNode tmp = this.headNode;
while(tmp != null) {
if(idx == 0) {return tmp.val;}
tmp = tmp.next;
idx --;
}
return -1;
}
}
本文探讨了如何使用Java实现链表中数字的随机获取,介绍了两种方法:一是将链表元素存入数组后随机选择,二是直接遍历链表按概率选取。通过优化构造函数和 getRandom 函数,两种方法的时间复杂度进行了比较,以提升随机获取效率。
847

被折叠的 条评论
为什么被折叠?



