Given An array of integers with possible duplicates, randomly output the index of a Given target number. You can assume this given target number must exist in the array. Note:the array size can be very large. Solution that uses too much extra space would not pass the judge. Example:int[] Nums =New int[] {1,2,3,3,3}; Solution Solution=Newsolution (nums);//pick (3) should return either index 2, 3, or 4 randomly. Each index should has equal probability of returning.Solution.pick (3);//pick (1) should return 0. Since in the array only nums[0] is equal to 1.Solution.pick (1);
Reservior Sampling
1 Public classSolution {2 int[] arr;3 random random;4 5 6 PublicSolution (int[] nums) {7arr =nums;8Random =NewRandom ();9 }Ten One Public intPickinttarget) { A intCount = 0; - intindex = 0; - for(inti=0; i<arr.length; i++) { the if(Arr[i] = =target) { -count++; - if(Random.nextint (count) = = 0) { -index =i; + } - } + } A returnindex; at } - } - - /** - * Your Solution Object would be instantiated and called as such: - * Solution obj = new solution (nums); in * int param_1 = Obj.pick (target); - */
Leetcode:random Pick Index