LeetCode 382 Linked List Random Node

Tech In Pieces發表於2020-12-10

Given a singly linked list, return a random node’s value from the linked list. Each node must have the same probability of being chosen.

idea:
uniformly random choose a node from linkedlist

/**
 * 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 {

    /** @param head The linked list's head.
        Note that the head is guaranteed to be not null, so it contains at least one node. */
    public Solution(ListNode head) {
        
    }
    
    /** Returns a random node's value. */
    public int getRandom() {
        
    }
}

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

get the whole length of the linkedlist, and random picked one index and move head pointer to there.
we need to proprecess to the length.

class Solution {

    /** @param head The linked list's head.
        Note that the head is guaranteed to be not null, so it contains at least one node. */
    ListNode head;
    int len;
    Random rand;
    public Solution(ListNode head) {
        this.head = head;
        rand = new Random();
        ListNode p = head;
        len = 1;
        while (p.next != null) {
            p = p.next;
            len++;
        }
    }
    
    /** Returns a random node's value. */
    public int getRandom() {
        int index = rand.nextInt(len);
        ListNode p = head;
        while (index > 0) {
            index--;
            p = p.next; 
        }
        return p.val;
    }
}

相關文章