Skip to content

Commit 7c1c591

Browse files
committed
Add problem 3159: Find Occurrences of an Element in an Array
1 parent 22732c5 commit 7c1c591

File tree

3 files changed

+66
-0
lines changed

3 files changed

+66
-0
lines changed

src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2112,6 +2112,7 @@ pub mod problem_3151_special_array_i;
21122112
pub mod problem_3152_special_array_ii;
21132113
pub mod problem_3153_sum_of_digit_differences_of_all_pairs;
21142114
pub mod problem_3158_find_the_xor_of_numbers_which_appear_twice;
2115+
pub mod problem_3159_find_occurrences_of_an_element_in_an_array;
21152116
pub mod problem_3350_adjacent_increasing_subarrays_detection_ii;
21162117

21172118
#[cfg(test)]
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
pub struct Solution;
2+
3+
// ------------------------------------------------------ snip ------------------------------------------------------ //
4+
5+
impl Solution {
6+
pub fn occurrences_of_element(nums: Vec<i32>, queries: Vec<i32>, x: i32) -> Vec<i32> {
7+
let mut nums = nums;
8+
let nums = &mut *nums;
9+
let mut count = 0;
10+
11+
for i in 0..nums.len() {
12+
if nums[i] == x {
13+
nums[count] = i as _;
14+
count += 1;
15+
}
16+
}
17+
18+
let indices = &mut nums[..count];
19+
20+
queries
21+
.into_iter()
22+
.map(|i| indices.get(i.cast_unsigned() as usize - 1).copied().unwrap_or(-1))
23+
.collect()
24+
}
25+
}
26+
27+
// ------------------------------------------------------ snip ------------------------------------------------------ //
28+
29+
impl super::Solution for Solution {
30+
fn occurrences_of_element(nums: Vec<i32>, queries: Vec<i32>, x: i32) -> Vec<i32> {
31+
Self::occurrences_of_element(nums, queries, x)
32+
}
33+
}
34+
35+
#[cfg(test)]
36+
mod tests {
37+
#[test]
38+
fn test_solution() {
39+
super::super::tests::run::<super::Solution>();
40+
}
41+
}
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
pub mod iterative;
2+
3+
pub trait Solution {
4+
fn occurrences_of_element(nums: Vec<i32>, queries: Vec<i32>, x: i32) -> Vec<i32>;
5+
}
6+
7+
#[cfg(test)]
8+
mod tests {
9+
use super::Solution;
10+
11+
pub fn run<S: Solution>() {
12+
let test_cases = [
13+
(
14+
(&[1, 3, 1, 7] as &[_], &[1, 3, 2, 4] as &[_], 1),
15+
&[0, -1, 2, -1] as &[_],
16+
),
17+
((&[1, 2, 3], &[10], 5), &[-1]),
18+
];
19+
20+
for ((nums, queries, x), expected) in test_cases {
21+
assert_eq!(S::occurrences_of_element(nums.to_vec(), queries.to_vec(), x), expected);
22+
}
23+
}
24+
}

0 commit comments

Comments
 (0)