题目
类型:链表
解题思路
链表长度只有 ,因此可以在初始化时遍历整条链表,将所有的链表值预处理到一个数组内。
在查询时随机一个下标,并将数组中对应下标内容返回出去。
代码
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
ListNode head;
Random random = new Random(20220116);
public Solution(ListNode _head) {
head = _head;
}
public int getRandom() {
int ans = 0, idx = 0;
ListNode t = head;
while (t != null && ++idx >= 0) {
if (random.nextInt(idx) == 0) ans = t.val;
t = t.next;
}
return ans;
}
}
/**
* Your Solution object will be instantiated and called as such:
* Solution obj = new Solution(head);
* int param_1 = obj.getRandom();
*/