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.

  • 相关阅读:
    python基础之数据类型
    简单猜年龄游戏
    python基础之变量
    Python3获取大量电影信息:调用API
    10分钟制作UWP汉堡菜单
    java 异常处理
    多态
    接口与继承
    数组及课后动手动脑
    String类型
  • 原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/12020690.html
Copyright © 2011-2022 走看看