|
| 1 | +package com.fishercoder.solutions; |
| 2 | + |
| 3 | +import java.util.ArrayList; |
| 4 | +import java.util.HashMap; |
| 5 | +import java.util.List; |
| 6 | +import java.util.Map; |
| 7 | + |
| 8 | +/**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. |
| 9 | +
|
| 10 | + Note: |
| 11 | + The array size can be very large. Solution that uses too much extra space will not pass the judge. |
| 12 | +
|
| 13 | + Example: |
| 14 | +
|
| 15 | + int[] nums = new int[] {1,2,3,3,3}; |
| 16 | + Solution solution = new Solution(nums); |
| 17 | +
|
| 18 | + // pick(3) should return either index 2, 3, or 4 randomly. Each index should have equal probability of returning. |
| 19 | + solution.pick(3); |
| 20 | +
|
| 21 | + // pick(1) should return 0. Since in the array only nums[0] is equal to 1. |
| 22 | + solution.pick(1);*/ |
| 23 | +public class _398 { |
| 24 | + |
| 25 | +//TODO: use reservoir sampling to solve it again |
| 26 | + |
| 27 | + class Solution { |
| 28 | + //brute force |
| 29 | + int[] input; |
| 30 | + java.util.Random rand = new java.util.Random(); |
| 31 | + |
| 32 | + public Solution(int[] nums) { |
| 33 | + input = nums; |
| 34 | + } |
| 35 | + |
| 36 | + public int pick(int target) { |
| 37 | + List<Integer> list = new ArrayList(); |
| 38 | + for (int i = 0; i < input.length; i++) { |
| 39 | + if (input[i] == target) { |
| 40 | + list.add(i); |
| 41 | + } |
| 42 | + } |
| 43 | + if (list.size() == 1) return list.get(0); |
| 44 | + int randomIndex = rand.nextInt(list.size()); |
| 45 | + return list.get(randomIndex); |
| 46 | + } |
| 47 | + } |
| 48 | + |
| 49 | + |
| 50 | + class Solution_MemoryLimitExceeded { |
| 51 | + |
| 52 | + private Map<Integer, List<Integer>> map = new HashMap(); |
| 53 | + java.util.Random rand = new java.util.Random(); |
| 54 | + |
| 55 | + public Solution_MemoryLimitExceeded(int[] nums) { |
| 56 | + for (int i = 0; i < nums.length; i++) { |
| 57 | + if (map.containsKey(nums[i])) { |
| 58 | + List<Integer> list = map.get(nums[i]); |
| 59 | + list.add(i); |
| 60 | + map.put(nums[i], list); |
| 61 | + } else { |
| 62 | + List<Integer> list = new ArrayList(); |
| 63 | + list.add(i); |
| 64 | + map.put(nums[i], list); |
| 65 | + } |
| 66 | + } |
| 67 | + } |
| 68 | + |
| 69 | + public int pick(int target) { |
| 70 | + List<Integer> list = map.get(target); |
| 71 | + if (list.size() == 1) return list.get(0); |
| 72 | + int randomIndex = rand.nextInt(list.size()); |
| 73 | + return list.get(randomIndex); |
| 74 | + } |
| 75 | + } |
| 76 | +} |
0 commit comments