zoukankan      html  css  js  c++  java
  • LeetCode 382. Linked List Random Node

    原题链接在这里:https://leetcode.com/problems/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();

    题解:

    First assign head value to res. count = 1.

    Then while current node next != null, move cur to next,  pick random number within [0, ++count).

    If it is equal to 0, update res.

    Time Complexity: getRandom, O(n). n is length of list.

    Space: O(1).

    AC Java:

     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     ListNode head;
    11     Random rand;
    12     
    13     /** @param head The linked list's head.
    14         Note that the head is guaranteed to be not null, so it contains at least one node. */
    15     public Solution(ListNode head) {
    16         this.head = head;
    17         rand = new Random();
    18     }
    19     
    20     /** Returns a random node's value. */
    21     public int getRandom() {
    22         ListNode cur = head;
    23         int res = cur.val;
    24         int count = 1;
    25         while(cur.next != null){
    26             cur = cur.next;
    27             if(rand.nextInt(++count) == 0){
    28                 res = cur.val;
    29             }
    30         }
    31         
    32         return res;
    33     }
    34 }
    35 
    36 /**
    37  * Your Solution object will be instantiated and called as such:
    38  * Solution obj = new Solution(head);
    39  * int param_1 = obj.getRandom();
    40  */

    类似Random Pick Index.

  • 相关阅读:
    mysql 函数 存储过程 事件(event) job 模板
    protobuf 无proto 解码 decode 语言 java python
    mitmproxy fiddler 抓包 填坑
    android adb 常用命令
    android机器人 模拟 踩坑过程
    RabbitMQ添加新用户并支持远程访问
    Windows下RabbitMQ安装及配置
    Java mybatis mysql 常用数据类型对应关系
    easyExcel 踩坑
    linux防火墙查看状态firewall、iptable
  • 原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/12020690.html
Copyright © 2011-2022 走看看