zoukankan      html  css  js  c++  java
  • 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 public class Solution {
    10     List<Integer> list = new ArrayList<>();
    11     
    12     /** @param head The linked list's head.
    13         Note that the head is guaranteed to be not null, so it contains at least one node. */
    14     public Solution(ListNode head) {
    15         while (head != null) {
    16             list.add(head.val);
    17             head = head.next;
    18         }
    19     }
    20     
    21     /** Returns a random node's value. */
    22     public int getRandom() {
    23         Random rand = new Random();
    24         int n = rand.nextInt(list.size());
    25         return list.get(n);
    26     }
    27 }
    28 
    29 /**
    30  * Your Solution object will be instantiated and called as such:
    31  * Solution obj = new Solution(head);
    32  * int param_1 = obj.getRandom();
    33  */
  • 相关阅读:
    身份证的测试用例
    集合
    网易考拉测试面试题整理
    linux基本指令分类
    网络编程
    设计模式
    MySQL中的索引
    MySQL中的事务
    Java判断字符串是否为乱码
    Activiti6.x删除外键
  • 原文地址:https://www.cnblogs.com/amazingzoe/p/6416727.html
Copyright © 2011-2022 走看看