382. Linked List Random Node (M)
来源:互联网 发布:美术生送什么礼物 知乎 编辑:程序博客网 时间:2024/06/07 23:47
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();
Subscribe to see which companies asked this question
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */public class Solution { ListNode head; Random r; /** @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() { r=new Random(); int count=0; ListNode now=head; int re=-1; while(now!=null){ if(r.nextInt(++count)==0) re=now.val; now=now.next; } return re; }}/** * Your Solution object will be instantiated and called as such: * Solution obj = new Solution(head); * int param_1 = obj.getRandom(); */
0 0
- 382. Linked List Random Node (M)
- 【leetcode】382. Linked List Random Node【M】【74】
- 382. Linked List Random Node
- 382. Linked List Random Node
- 382. Linked List Random Node
- 382. Linked List Random Node
- 382. Linked List Random Node
- 382. Linked List Random Node
- 382. Linked List Random Node
- 382. Linked List Random Node
- 382. Linked List Random Node
- 382. Linked List Random Node
- 382. Linked List Random Node**
- 382. Linked List Random Node
- 382. Linked List Random Node
- 382. Linked List Random Node
- 382. Linked List Random Node
- 382. Linked List Random Node
- py2.7 : 《机器学习实战》 Logistic回归 1.22号 5.3 分析数据:随机梯度上升
- POJ1698 Alice's Chance 最大流Dinic
- pytorch 学习笔记(一)
- Leetcode 129. Sum Root to Leaf Numbers
- Cisco VPP "fib.h"中文对照
- 382. Linked List Random Node (M)
- cocos2d-lua cc.CallFunc:create 带参数回调
- UVa442矩阵连乘
- venom结合Metasploit绕过360安全卫士
- PL/SqlDeveloper安装(Oracle11g服务安装完后客户端安装)
- ELF文件格式概述
- 程序员面试金典——解题总结: 9.18高难度题 18.8给定一个字符串s和一个包含较短字符串的数组T,设计一个方法,根据T中的每一个较短字符串,对s进行搜索
- C++ Qt Game Tutorial 5 - Adding Enemies
- 深挖SpringMVC_05_SpringMVC接收表单bean