-
Notifications
You must be signed in to change notification settings - Fork 21
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add problem 1991: Find the Middle Index in Array
- Loading branch information
Showing
3 changed files
with
58 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
39 changes: 39 additions & 0 deletions
39
src/problem_1991_find_the_middle_index_in_array/iterative.rs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,39 @@ | ||
pub struct Solution; | ||
|
||
// ------------------------------------------------------ snip ------------------------------------------------------ // | ||
|
||
impl Solution { | ||
pub fn find_middle_index(nums: Vec<i32>) -> i32 { | ||
let total_sum = nums.iter().sum::<i32>(); | ||
let mut result = -1; | ||
let mut sum = 0; | ||
|
||
for (i, num) in (0..).zip(nums) { | ||
if sum + sum + num == total_sum { | ||
result = i; | ||
|
||
break; | ||
} | ||
|
||
sum += num; | ||
} | ||
|
||
result | ||
} | ||
} | ||
|
||
// ------------------------------------------------------ snip ------------------------------------------------------ // | ||
|
||
impl super::Solution for Solution { | ||
fn find_middle_index(nums: Vec<i32>) -> i32 { | ||
Self::find_middle_index(nums) | ||
} | ||
} | ||
|
||
#[cfg(test)] | ||
mod tests { | ||
#[test] | ||
fn test_solution() { | ||
super::super::tests::run::<super::Solution>(); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,18 @@ | ||
pub mod iterative; | ||
|
||
pub trait Solution { | ||
fn find_middle_index(nums: Vec<i32>) -> i32; | ||
} | ||
|
||
#[cfg(test)] | ||
mod tests { | ||
use super::Solution; | ||
|
||
pub fn run<S: Solution>() { | ||
let test_cases = [(&[2, 3, -1, 8, 4] as &[_], 3), (&[1, -1, 4], 2), (&[2, 5], -1)]; | ||
|
||
for (nums, expected) in test_cases { | ||
assert_eq!(S::find_middle_index(nums.to_vec()), expected); | ||
} | ||
} | ||
} |