382. Linked List Random Node
Given a singly linked list, return a random node's value from the linked list. Each node must have the same probability of being chosen.
Follow up:
What if the linked list is extremely large and its length is unknown to you? Could you solve this efficiently without using extra space?
Example:
// Init a singly linked list [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() should return either 1, 2, or 3 randomly. Each element should have equal probability of returning. solution.getRandom();
含义:给了我们一个链表,让我们随机返回一个节点。要求每个节点返回的概率是相同的
1 /** 2 * Definition for singly-linked list. 3 * public class ListNode { 4 * int val; 5 * ListNode next; 6 * ListNode(int x) { val = x; } 7 * } 8 */ 9 class Solution { 10 ArrayList<Integer> nums; 11 HashMap<Integer, Integer> locs; 12 java.util.Random rand = new java.util.Random(); 13 14 /** 15 * Initialize your data structure here. 16 */ 17 public RandomizedSet() { 18 nums = new ArrayList<Integer>(); 19 locs = new HashMap<Integer, Integer>(); 20 } 21 22 /** 23 * Inserts a value to the set. Returns true if the set did not already contain the specified element. 24 */ 25 public boolean insert(int val) { 26 if (locs.containsKey(val)) return false; 27 locs.put(val, nums.size()); 28 nums.add(val); 29 return true; 30 } 31 32 /** 33 * Removes a value from the set. Returns true if the set contained the specified element. 34 */ 35 public boolean remove(int val) { 36 if (!locs.containsKey(val)) return false; 37 int loc = locs.get(val); 38 if (loc < nums.size() - 1) { // not the last one than swap the last one with this val 39 int lastone = nums.get(nums.size() - 1); 40 nums.set(loc, lastone); 41 locs.put(lastone, loc); 42 } 43 locs.remove(val); 44 nums.remove(nums.size() - 1); 45 return true; 46 } 47 48 /** 49 * Get a random element from the set. 50 */ 51 public int getRandom() { 52 return nums.get(rand.nextInt(nums.size())); 53 } 54 } 55 56 /** 57 * Your Solution object will be instantiated and called as such: 58 * Solution obj = new Solution(head); 59 * int param_1 = obj.getRandom(); 60 */
分类:
leetcode_other
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!