0
点赞
收藏
分享

微信扫一扫

力扣382.链表随机节点

笙烛 2024-02-24 阅读 11

文章目录

题目描述

思路

复杂度

时间复杂度:

空间复杂度:

Code

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
    ListNode *head;
public:
    Solution(ListNode* head) {
        this -> head = head;
    }

    /**
     * Returns a random node of the linked list
     *
     * @return int
     */
    int getRandom() {
        int res = 0;
        ListNode* node = head;
        int i;
        for (int i = 1; node != nullptr; ++i) {
            if (rand() % i == 0) {
                res = node -> val;
            }
            node = node -> next;
        }
        return res;
    }
};


/**
 * Your Solution object will be instantiated and called as such:
 * Solution* obj = new Solution(head);
 * int param_1 = obj->getRandom();
 */
举报

相关推荐

0 条评论