• leetcode382 链表随机节点


    思路:

    蓄水池采样。

    实现:

     1 /**
     2  * Definition for singly-linked list.
     3  * struct ListNode {
     4  *     int val;
     5  *     ListNode *next;
     6  *     ListNode() : val(0), next(nullptr) {}
     7  *     ListNode(int x) : val(x), next(nullptr) {}
     8  *     ListNode(int x, ListNode *next) : val(x), next(next) {}
     9  * };
    10  */
    11 class Solution {
    12 public:
    13     int len=0;
    14     ListNode*h=NULL;
    15     Solution(ListNode* head) {
    16         h=head;
    17         while(head){
    18             len++;
    19             head=head->next;
    20         }
    21     }
    22     
    23     int getRandom() {
    24         int cur=0;
    25         ListNode*tmp=h;
    26         for(int i=1;i<=len;i++){
    27             int num=rand()%i;
    28             if(num==0)cur=tmp->val;
    29             tmp=tmp->next;
    30         }
    31         return cur;
    32     }
    33 };
    34 
    35 /**
    36  * Your Solution object will be instantiated and called as such:
    37  * Solution* obj = new Solution(head);
    38  * int param_1 = obj->getRandom();
    39  */
  • 相关阅读:
    hadoop
    spark
    docfetcher
    redis参考资料
    Redis系列-存储篇sorted set主要操作函数小结
    predis操作大全
    composer安装使用
    寒假作业2
    寒假作业随笔
    面向对象寒假作业编程题
  • 原文地址:https://www.cnblogs.com/wangyiming/p/16218698.html
Copyright © 2020-2023  润新知