if (rand.nextInt(++count) == count-1) result = i;


  • 0
    G

    The most important confusion for this question is
    "What if the count is 2 or 10 (when x is repeated 10 times) " and we are only checking for
    rand.nextInt(++count) == 0 ??

    So, this is for an understanding of the above idea..

    public class Solution {
        int[] nums;
        Random rand;
        public Solution(int[] nums) {
            this.nums = nums;
            this.rand = new Random();
        }
         public int pick(int target) {
            int result = -1;
            int count = 0;
            for (int i = 0; i < nums.length; i++) {
                if (nums[i] != target)
                    continue;
                if (rand.nextInt(++count) == count-1)
                    result = i;
            }
            
            return result;
        }
    }
    

Log in to reply
 

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