java solution,but got wrong answer,why


  • 0
    P

    why it's wrong
    ...
    /**

    • Definition for singly-linked list.

    • public class ListNode {

    • int val;
      
    • ListNode next;
      
    • ListNode(int x) { val = x; }
      
    • }
      */
      public class Solution {
      private ListNode list;
      private Random rand;

      /** @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) {
      list = head;
      rand = new Random();
      }

      /** Returns a random node's value. */
      public int getRandom() {
      int count = 1;
      ListNode p = list.next;
      int select = list.val;
      while(p != null){
      count ++;
      if(rand.nextDouble() <= (1 / count) ){
      select = p.val;
      }
      p = p.next;
      }
      return select;
      }
      }

    /**

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

Log in to reply
 

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