本文主要是介绍C++ | Leetcode C++题解之第382题链表随机节点,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
题目:
题解:
class Solution {ListNode *head;public:Solution(ListNode *head) {this->head = head;}int getRandom() {int i = 1, ans = 0;for (auto node = head; node; node = node->next) {if (rand() % i == 0) { // 1/i 的概率选中(替换为答案)ans = node->val;}++i;}return ans;}
};
这篇关于C++ | Leetcode C++题解之第382题链表随机节点的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!