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