Skip to content

Commit 1ba1d8b

Browse files
committed
Create 398-random-pick-index.rs
1 parent 21e818c commit 1ba1d8b

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

398-random-pick-index.rs

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
use std::collections::HashMap;
2+
3+
struct Solution {
4+
mmp: HashMap<i32, Vec<usize>>
5+
}
6+
7+
impl Solution {
8+
9+
fn new(nums: Vec<i32>) -> Self {
10+
let mut mmp = HashMap::new();
11+
for (i, num) in nums.iter().enumerate() {
12+
mmp.entry(*num).or_insert(Vec::new()).push(i);
13+
}
14+
Solution {
15+
mmp: mmp
16+
}
17+
}
18+
19+
fn pick(&mut self, target: i32) -> i32 {
20+
self.mmp.get_mut(&target).unwrap().rotate_right(1);
21+
self.mmp[&target][0] as i32
22+
}
23+
}
24+
25+
fn main() {
26+
let mut obj = Solution::new(vec![1, 2, 3, 3, 3]);
27+
println!("{:?}", obj.pick(3));
28+
println!("{:?}", obj.pick(1));
29+
println!("{:?}", obj.pick(3));
30+
println!("{:?}", obj.pick(3));
31+
println!("{:?}", obj.pick(3));
32+
println!("{:?}", obj.pick(3));
33+
println!("{:?}", obj.pick(3));
34+
println!("{:?}", obj.pick(3));
35+
println!("{:?}", obj.pick(3));
36+
println!("{:?}", obj.pick(3));
37+
}

0 commit comments

Comments
 (0)