Java Solution - Optimized for calling random


  • 0
    D
    public class Solution {
    
        List<Integer> nodeValues;
    
        /** @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) {
            this.nodeValues = new ArrayList<Integer>();
            ListNode curr = head;
            while (curr != null) {
                nodeValues.add(curr.val);
                curr = curr.next;
            }
        }
        
        /** Returns a random node's value. */
        public int getRandom() {
            Random rand = new Random();
            int index = rand.nextInt(nodeValues.size());
            return nodeValues.get(index);
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.