Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit0459666

Browse files
refactor 398
1 parent9703a71 commit0459666

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
packagecom.fishercoder.solutions;
22

33
importjava.util.ArrayList;
4-
importjava.util.HashMap;
54
importjava.util.List;
6-
importjava.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
publicclass_398 {
2426

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

27-
classSolution {
29+
publicstaticclassSolution {
2830
//brute force
2931
int[]input;
3032
java.util.Randomrand =newjava.util.Random();
@@ -47,34 +49,4 @@ public int pick(int target) {
4749
returnlist.get(randomIndex);
4850
}
4951
}
50-
51-
52-
classSolutionMemoryLimitExceeded {
53-
54-
privateMap<Integer,List<Integer>>map =newHashMap();
55-
java.util.Randomrand =newjava.util.Random();
56-
57-
publicSolutionMemoryLimitExceeded(int[]nums) {
58-
for (inti =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 =newArrayList();
65-
list.add(i);
66-
map.put(nums[i],list);
67-
}
68-
}
69-
}
70-
71-
publicintpick(inttarget) {
72-
List<Integer>list =map.get(target);
73-
if (list.size() ==1) {
74-
returnlist.get(0);
75-
}
76-
intrandomIndex =rand.nextInt(list.size());
77-
returnlist.get(randomIndex);
78-
}
79-
}
8052
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp