Skip to content

Commit 0459666

Browse files
refactor 398
1 parent 9703a71 commit 0459666

File tree

1 file changed

+7
-35
lines changed
  • src/main/java/com/fishercoder/solutions

1 file changed

+7
-35
lines changed
Lines changed: 7 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,13 @@
11
package com.fishercoder.solutions;
22

33
import java.util.ArrayList;
4-
import java.util.HashMap;
54
import java.util.List;
6-
import java.util.Map;
75

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.
6+
/**
7+
* 398. Random Pick Index
8+
*
9+
* Given an array of integers with possible duplicates,
10+
* randomly output the index of a given target number. You can assume that the given target number must exist in the array.
911
1012
Note:
1113
The array size can be very large. Solution that uses too much extra space will not pass the judge.
@@ -22,9 +24,9 @@
2224
solution.pick(1);*/
2325
public class _398 {
2426

25-
//TODO: use reservoir sampling to solve it again
27+
//TODO: use reservoir sampling to solve it again
2628

27-
class Solution {
29+
public static class Solution {
2830
//brute force
2931
int[] input;
3032
java.util.Random rand = new java.util.Random();
@@ -47,34 +49,4 @@ public int pick(int target) {
4749
return list.get(randomIndex);
4850
}
4951
}
50-
51-
52-
class SolutionMemoryLimitExceeded {
53-
54-
private Map<Integer, List<Integer>> map = new HashMap();
55-
java.util.Random rand = new java.util.Random();
56-
57-
public SolutionMemoryLimitExceeded(int[] nums) {
58-
for (int i = 0; i < nums.length; i++) {
59-
if (map.containsKey(nums[i])) {
60-
List<Integer> list = map.get(nums[i]);
61-
list.add(i);
62-
map.put(nums[i], list);
63-
} else {
64-
List<Integer> list = new ArrayList();
65-
list.add(i);
66-
map.put(nums[i], list);
67-
}
68-
}
69-
}
70-
71-
public int pick(int target) {
72-
List<Integer> list = map.get(target);
73-
if (list.size() == 1) {
74-
return list.get(0);
75-
}
76-
int randomIndex = rand.nextInt(list.size());
77-
return list.get(randomIndex);
78-
}
79-
}
8052
}

0 commit comments

Comments
 (0)