8000 src/bin/random-pick-index.rs · bestgopher/leetcode@ac3c93c · GitHub
[go: up one dir, main page]

Skip to content

Commit ac3c93c

Browse files
committed
src/bin/random-pick-index.rs
1 parent e6990c0 commit ac3c93c

File tree

1 file changed

+29
-2
lines changed

1 file changed

+29
-2
lines changed

src/bin/random-pick-index.rs

Lines changed: 29 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ fn main() {}
55
* let obj = Solution::new(nums);
66
* let ret_1: i32 = obj.pick(target);
77
*/
8-
struct Solution {
8+
struct Solution1 {
99
index_map: std::collections::HashMap<i32, Vec<usize>>
1010
}
1111

@@ -14,7 +14,7 @@ struct Solution {
1414
* `&self` means the method takes an immutable reference.
1515
* If you need a mutable reference, change it to `&mut self` instead.
1616
*/
17-
impl Solution {
17+
impl Solution1 {
1818
fn new(nums: Vec<i32>) -> Self {
1919
let mut index_map = std::collections::HashMap::new();
2020

@@ -40,3 +40,30 @@ impl Solution {
4040
}
4141
}
4242
}
43+
44+
struct Solution {
45+
nums: Vec<i32>
46+
}
47+
48+
impl Solution {
49+
fn new(nums: Vec<i32>) -> Self {
50+
Self { nums }
51+
}
52+
53+
fn pick(&self, target: i32) -> i32 {
54+
use rand::Rng;
55+
let mut n = 0;
56+
let mut r = 0;
57+
58+
for i in 0..self.nums.len() {
59+
if self.nums[i] == target {
60+
n += 1;
61+
if rand::thread_rng().gen_range(0..n) == 0 {
62+
r = i as i32;
63+
}
64+
}
65+
}
66+
67+
r
68+
}
69+
}

0 commit comments

Comments
 (0)
0