项目作者: eMahtab

项目描述 :
Random pick index
高级语言:
项目地址: git://github.com/eMahtab/random-pick-index.git
创建时间: 2020-06-20T13:45:15Z
项目社区:https://github.com/eMahtab/random-pick-index

开源协议:

下载


Random pick index

https://leetcode.com/problems/random-pick-index

Given an array of integers with possible duplicates, randomly output the index of a given target number. You can assume that the given target number must exist in the array.

Note:

The array size can be very large. Solution that uses too much extra space will not pass the judge.

  1. Example:
  2. int[] nums = new int[] {1,2,3,3,3};
  3. Solution solution = new Solution(nums);
  4. // pick(3) should return either index 2, 3, or 4 randomly. Each index should have equal probability of returning.
  5. solution.pick(3);
  6. // pick(1) should return 0. Since in the array only nums[0] is equal to 1.
  7. solution.pick(1);

Implementation 1 : Naive

  1. class Solution {
  2. Map<Integer,List<Integer>> map;
  3. Random random;
  4. public Solution(int[] nums) {
  5. map = new HashMap<Integer, List<Integer>>();
  6. random = new Random();
  7. for(int i = 0; i < nums.length; i++) {
  8. map.putIfAbsent(nums[i], new ArrayList<Integer>());
  9. map.get(nums[i]).add(i);
  10. }
  11. }
  12. public int pick(int target) {
  13. int occurances = map.get(target).size();
  14. int randomIndex = random.nextInt(occurances);
  15. return map.get(target).get(randomIndex);
  16. }
  17. }
  18. /**
  19. * Your Solution object will be instantiated and called as such:
  20. * Solution obj = new Solution(nums);
  21. * int param_1 = obj.pick(target);
  22. */

Implementation 2 : No Extra Space

  1. class Solution {
  2. int[] nums;
  3. Random random;
  4. public Solution(int[] nums) {
  5. this.nums = nums;
  6. random = new Random();
  7. }
  8. public int pick(int target) {
  9. int count = 0;
  10. int index = 0;
  11. for (int i = 0; i < nums.length; i++) {
  12. if(nums[i] == target) {
  13. count++;
  14. // This if changes the probability of an index i to be selected
  15. if(random.nextInt(count) == 0) {
  16. index = i;
  17. }
  18. }
  19. }
  20. return index;
  21. }
  22. }
  23. /**
  24. * Your Solution object will be instantiated and called as such:
  25. * Solution obj = new Solution(nums);
  26. * int param_1 = obj.pick(target);
  27. */

Tip :
To better understand the second implementation, run through some examples.
e.g. int[] nums = [1, 2, 3] , target = 3
e.g. int[] nums = [1, 2, 3, 3] , target = 3
e.g. int[] nums = [1, 2, 3, 3, 3] , target = 3

References :

https://www.youtube.com/watch?v=Tt1j0mVzHdg