给出一个链表,随机返回链表中的一个数字,平均分布。
思路:
- 把链表的数字保存到一个数组里面,然后随机取数组下标,得到数字
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;
}
}