Skip to content

Commit 472f740

Browse files
committed
src/bin/random-pick-index.rs
1 parent fea7f27 commit 472f740

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

src/bin/random-pick-index.rs

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
fn main() {}
2+
3+
/**
4+
* Your Solution object will be instantiated and called as such:
5+
* let obj = Solution::new(nums);
6+
* let ret_1: i32 = obj.pick(target);
7+
*/
8+
struct Solution {
9+
index_map: std::collections::HashMap<i32, Vec<usize>>
10+
}
11+
12+
13+
/**
14+
* `&self` means the method takes an immutable reference.
15+
* If you need a mutable reference, change it to `&mut self` instead.
16+
*/
17+
impl Solution {
18+
fn new(nums: Vec<i32>) -> Self {
19+
let mut index_map = std::collections::HashMap::new();
20+
21+
nums
22+
.into_iter()
23+
.enumerate()
24+
.for_each(|(index, value)| {
25+
index_map.entry(value)
26+
.and_modify(|y: &mut Vec<usize>| y.push(index)).or_insert(vec![index]);
27+
});
28+
29+
Self { index_map }
30+
}
31+
32+
fn pick(&self, target: i32) -> i32 {
33+
use rand::Rng;
34+
35+
match self.index_map.get(&target) {
36+
Some(x) => {
37+
x[rand::thread_rng().gen_range(0..x.len())] as i32
38+
}
39+
None => 0
40+
}
41+
}
42+
}

0 commit comments

Comments
 (0)