Leetcode Linked List Random Node C++(蓄水池抽样算法)

leetcode上一道典型的关于蓄水池抽样算法,关于蓄水池抽样算法,有一篇博客讲的非常好
http://blog.csdn.net/huagong_adu/article/details/7619665

理清楚了算法思路后
我们来看看这道题的题意

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

利用蓄水池抽样算法,写出可以AC的代码,这里想多说一句,还是那句话,注意细节,bug往往出现在细节处,还有如果使用MAC的同学想要用gdb调试的话,可以尝试下Xcode中带的命令行工具中的lldb,使用方法与gdb相同。

下面的代码中Solution部分是可以AC的代码,同时还有附带的测试用例。

/***********************
Leetcode 382 Linked List Random Node
algorithms : reserviors sampling
author : xiaolewen_bupt
time complexity : O(N), space complexity : O(1)
test the leetcode's 
linkList problem 
in the loacal environment
***********************/


#include <stdlib.h>
#include <time.h>
#include <iostream>
using namespace std;
struct ListNode
{
    int val;
    ListNode *next;
    ListNode(int x): val(x),next(NULL) {}
};


void addToTail(ListNode **head,int val)
{
    ListNode *node =new ListNode(val);
    if (!*head)                         
    {
        *head = node;
    }
    else
    {
        ListNode *tmp=*head;
        while (tmp->next)
            tmp=tmp->next;
        tmp->next=node;
    }

}

void printList(ListNode *head)
{
    ListNode* tmp;
    tmp=head;
    if (tmp==NULL)
        cout<<"empty list";
    else
    {
        while (tmp!=NULL)
        {
            cout<<tmp->val<<',';
            tmp=tmp->next;
        }
        cout<<endl;
    }

}

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    /** @param head The linked list's head.
        Note that the head is guaranteed to be not null, so it contains at least one node. */
    Solution(ListNode* head) {
        iter = head;
        head_temp = head;
    }

    /** Returns a random node's value. */
    int getRandom() {
        resetIter(&iter);
        //srand(time(NULL));
        int res = iter -> val;
        iter = iter -> next;
        for(int i = 1; iter != NULL; i++)
        {
            int randomNum = random(0, i);
            if(randomNum < 1)
                res = iter -> val;
            iter = iter -> next;
        }
        return res;
    }
private:
    void resetIter(ListNode** iter)  //if you want modify a pointer , please pass the pointer's pointer to the function
    {
        *iter = head_temp;
    }
    ListNode *head_temp;
    ListNode *iter;
    int random(int low, int high)
    {
        if(low > high)
            random(high, low);
        int res = low + rand() % (high - low + 1);
        return res;
    }
};

/**
 * Your Solution object will be instantiated and called as such:
 * Solution obj = new Solution(head);
 * int param_1 = obj.getRandom();
 */
int main()
{
    int lt=time(NULL);
    srand(lt);
    int len = rand()%20;
    cout<<len<< endl;
    if (len<1)
        return 0;
    ListNode *root=NULL;
    for (int i=0;i<len;i++)
        addToTail(&root,rand()%100);
    printList(root);
    // fill the parameters in your function below
    Solution* solution = new Solution(root);
    cout << solution -> getRandom() << endl;
    cout << solution -> getRandom() << endl;
    cout << solution -> getRandom() << endl;
    cout << solution -> getRandom() << endl;
    delete solution;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值