Leetcode:random Pick Index

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.