Leetcode-随机数:382. 链表随机节点、
382. 链表随机节点
给定一个单链表,随机选择链表的一个节点,并返回相应的节点值。保证每个节点被选的概率一样。
进阶:
如果链表十分大且长度未知,如何解决这个问题?你能否使用常数级空间复杂度实现?
示例:
// 初始化一个单链表 [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.
* 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;
/** @param head The linked list's head.
Note that the head is guaranteed to be not null, so it contains at least one node. */
public Solution(ListNode head) {
this.head=head;
}
/** Returns a random node's value. */
public int getRandom() {
Random r = new Random();
int i = 0, res = 0;
ListNode p = head;
// while 循环遍历链表
while (p != null) {
// 生成一个 [0, i) 之间的整数
// 这个整数等于 0 的概率就是 1/i
if (r.nextInt(++i) == 0) {
res = p.val;
}
p = p.next;
}
return res;
}
}
/**
* Your Solution object will be instantiated and called as such:
* Solution obj = new Solution(head);
* int param_1 = obj.getRandom();
*/398. 随机数索引
给定一个可能含有重复元素的整数数组,要求随机输出给定的数字的索引。 您可以假设给定的数字一定存在于数组中。
注意:
数组大小可能非常大。 使用太多额外空间的解决方案将不会通过测试。
示例:
int[] nums = new int[] {1,2,3,3,3};
Solution solution = new Solution(nums);
// pick(3) 应该返回索引 2,3 或者 4。每个索引的返回概率应该相等。
solution.pick(3);
// pick(1) 应该返回 0。因为只有nums[0]等于1。
solution.pick(1);
解题思路
将每个元素对应的索引利用hashmap存在一个arraylist中
然后生成list的随机索引,按下标取元素
class Solution {
HashMap<Integer,ArrayList<Integer>> map=new HashMap<>();
public Solution(int[] nums) {
for(int i=0;i<nums.length;i++){
Integer num=nums[i];
ArrayList<Integer> list=map.getOrDefault(num,new ArrayList<Integer>());
list.add(i);
map.put(num,list);
}
}
public int pick(int target) {
ArrayList<Integer> list_target=map.get(target);
Random r = new Random();
Integer temp=r.nextInt(list_target.size());
return list_target.get(temp);
}
}
/**
* Your Solution object will be instantiated and called as such:
* Solution obj = new Solution(nums);
* int param_1 = obj.pick(target);
*/Leetcode-牛客-刷题笔记 文章被收录于专栏
本专栏主要用于分享栏主在准备java后端面试过程中的刷题笔记
查看11道真题和解析