Solve two-sum.
This commit is contained in:
parent
763a55bab8
commit
a651f9ed80
|
@ -0,0 +1 @@
|
|||
pub mod two_sum;
|
|
@ -0,0 +1,26 @@
|
|||
use std::convert::TryInto;
|
||||
|
||||
pub fn two_sum(numbers: Vec<i32>, target: i32) -> Vec<i32> {
|
||||
for (index_1, number_1) in numbers.iter().enumerate() {
|
||||
for (index_2, number_2) in numbers.iter().enumerate() {
|
||||
if index_1 == index_2 {
|
||||
continue;
|
||||
}
|
||||
|
||||
if number_1 + number_2 == target {
|
||||
return vec![index_1.try_into().unwrap(), index_2.try_into().unwrap()];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
panic!("No pair of numbers found that sum to {}", target)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_two_sum() {
|
||||
assert_eq!(two_sum(vec![2, 7, 11, 15], 9), [0, 1]);
|
||||
assert_eq!(two_sum(vec![3, 2, 4], 6), [1, 2]);
|
||||
assert_eq!(two_sum(vec![3, 3], 6), [0, 1]);
|
||||
assert_eq!(two_sum(vec![3, 2, 3], 6), [0, 2]);
|
||||
assert_eq!(two_sum(vec![-3, 4, 3, 90], 0), [0, 2]);
|
||||
}
|
Loading…
Reference in New Issue