File tree 1 file changed +31
-5
lines changed
scripts/algorithms/R/Random Pick Index
1 file changed +31
-5
lines changed Original file line number Diff line number Diff line change 1
1
class Solution :
2
+
2
3
def __init__ (self , nums : List [int ]):
3
- self .multimap = defaultdict (list )
4
- for i , n in enumerate (nums ):
5
- self .multimap [n ].append (i )
4
+ #self.nums = nums
5
+ #create a hash of values with their list of indices
6
+ self .map = defaultdict (list )
7
+ for i ,v in enumerate (nums ):
8
+ self .map [v ].append (i )
9
+
6
10
7
- # O(1) time complexity
8
11
def pick (self , target : int ) -> int :
9
- return random .choice (self .multimap [target ])
12
+ return random .sample (self .map [target ],1 )[0 ]
13
+ '''
14
+ reservoir = 0
15
+ count = 0
16
+ for i in range(len(self.nums)):
17
+ if self.nums[i] == target:
18
+ count+=1
19
+ if random.random() < 1/count:
20
+ reservoir = i
21
+ return reservoir
22
+
23
+
24
+ samp = []
25
+ for i in range(len(self.nums)):
26
+ if self.nums[i] == target:
27
+ samp.append(i)
28
+ return (random.sample(samp,1))[0]
29
+ '''
30
+
31
+
32
+
33
+ # Your Solution object will be instantiated and called as such:
34
+ # obj = Solution(nums)
35
+ # param_1 = obj.pick(target)
You can’t perform that action at this time.
0 commit comments