Skip to content

Commit 349a048

Browse files
committed
solve(1848): implement solution with iterator
1 parent bc20f06 commit 349a048

File tree

2 files changed

+27
-0
lines changed

2 files changed

+27
-0
lines changed
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
use crate::solutions::Solution;
2+
3+
impl Solution {
4+
pub fn get_min_distance(nums: Vec<i32>, target: i32, start: i32) -> i32 {
5+
let mut min_distance = nums.len() as i32;
6+
7+
for (i, &num) in nums.iter().enumerate() {
8+
if num == target {
9+
min_distance = min_distance.min((i as i32 - start).abs())
10+
}
11+
}
12+
13+
min_distance
14+
}
15+
}
16+
17+
#[test]
18+
fn test() {
19+
assert_eq!(Solution::get_min_distance(vec![1, 2, 3, 4, 5], 5, 3), 1);
20+
assert_eq!(Solution::get_min_distance(vec![1], 1, 0), 0);
21+
assert_eq!(
22+
Solution::get_min_distance(vec![1, 1, 1, 1, 1, 1, 1, 1, 1, 1], 1, 1),
23+
0
24+
);
25+
assert_eq!(Solution::get_min_distance(vec![5, 3, 6], 5, 2), 2);
26+
}

src/solutions/mod.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ pub mod _0009_palindrome_number;
33
pub mod _0020_valid_parentheses;
44
pub mod _0026_remove_duplicates_from_sorted_array;
55
pub mod _0027_remove_element;
6+
pub mod _1848_minimum_distance_to_the_target_element;
67
pub mod _3046_split_the_array;
78

89
pub struct Solution {}

0 commit comments

Comments
 (0)