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

    Problem:

    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();
    

    思路

    Solution (C++):

    ListNode* u;
    Solution(ListNode* head) {
        u = head;
    }
    
    /** Returns a random node's value. */
    int getRandom() {
        ListNode* v = u;
        int res = v->val, len = 1;
        while (v) {
            if (rand() % len == 0) {
                res = v->val;
            }
            len++;
            v = v->next;
        }
        return res;
    }
    

    性能

    Runtime: 40 ms  Memory Usage: 14 MB

    思路

    Solution (C++):

    
    

    性能

    Runtime: ms  Memory Usage: MB

    相关链接如下:

    知乎:littledy

    欢迎关注个人微信公众号:小邓杂谈,扫描下方二维码即可

    作者:littledy
    本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接,否则保留追究法律责任的权利。
  • 相关阅读:
    软件工程实践2019第一次作业
    SDN第三次作业
    SDN第二次作业
    SDN第一次作业
    软工第二次结对
    #软件工程第三次作业
    2019软件工程第一次作业
    php-长文章分页函数
    Sqlilab靶机配置
    目录遍历(复现及修复)
  • 原文地址:https://www.cnblogs.com/dysjtu1995/p/12665806.html
Copyright © 2011-2022 走看看