27 lines
748 B
Rust
27 lines
748 B
Rust
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]);
|
|
}
|