Leetcode 382. 链表随机节点 解题思路及C++实现
生活随笔
收集整理的這篇文章主要介紹了
Leetcode 382. 链表随机节点 解题思路及C++实现
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
解題思路:
因為題目中要求需要常數級的空間復雜度,所以就需要計算鏈表長度了。
?
/*** Definition for singly-linked list.* struct ListNode {* int val;* ListNode *next;* ListNode(int x) : val(x), next(NULL) {}* };*/ class Solution { public:int n = 0; //用于記錄鏈表長度,用于實現等概率ListNode* root;/** @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) {root = head;while(head){n++;head = head->next;}}/** Returns a random node's value. */int getRandom() {int tmp = 0 + rand() % n; //n是整數的范圍ListNode* ln = root;while(tmp > 0){ln = ln->next;tmp--;}return ln->val;} };/*** Your Solution object will be instantiated and called as such:* Solution* obj = new Solution(head);* int param_1 = obj->getRandom();*/?
?
總結
以上是生活随笔為你收集整理的Leetcode 382. 链表随机节点 解题思路及C++实现的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Leetcode 375. 猜数字大小
- 下一篇: Leetcode 398. 随机数索引