This is a similar problem with 398. Random Pick Index

The following is my solution, which is easy to undersand:

class Solution {
    int count = 0;
    Random r = new Random();
    ListNode head;
    public Solution(ListNode head) {
        this.head = head;
        ListNode dummy = head;
        while(dummy!=null){
            dummy=dummy.next;
            count++;
        }
    }
    
    public int getRandom() {
        int random = r.nextInt(count);
        ListNode dummy = head;
        for(int i=0;i<random;i++){
            dummy=dummy.next;
        }
        return dummy.val;
    }
}

This is another solution:

class Solution {
    Random r = new Random();
    ListNode head;
    public Solution(ListNode head) {
       this.head = head;
    }
    
    public int getRandom() {
        int count=0;
        ListNode dummy = head;
        int res =head.val;
        while(dummy!=null){
            count++;
            int random = r.nextInt(count);
            if(random==0)
                res = dummy.val;
            dummy = dummy.next;
        }
        return res;
    }
}

 

posted on 2022-02-25 08:35  阳光明媚的菲越  阅读(27)  评论(0编辑  收藏  举报