0
点赞
收藏
分享

微信扫一扫

每日一题 leetcode 382. 链表随机节点 java题解

Greatiga 2022-01-16 阅读 40

题目

https://leetcode-cn.com/problems/linked-list-random-node/

代码

Java中的Random

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    ListNode head;
    Random random;
    public Solution(ListNode head) {
        this.head=head;
        this.random=new Random();
    }
    
    public int getRandom() {
        int res=0;
        int i=1;
        for(ListNode node=head;node!=null;node=node.next){
            if(random.nextInt(i)==0){//生成[0,i)
                res=node.val;
            }
            i++;
        }
        return res;
    }
}

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

相关推荐

0 条评论