leet-code/two-sum-ii-input-array-is-s.../sol.rs

20 lines
619 B
Rust
Raw Permalink Normal View History

2022-06-09 14:45:14 +00:00
impl Solution {
pub fn two_sum(numbers: Vec<i32>, target: i32) -> Vec<i32> {
let (mut front, mut back) = (
numbers.iter(),
numbers.iter().rev()
);
let (mut f_idx, mut f) = (1, *front.next().unwrap());
let (mut b_idx, mut b) = (numbers.len() as i32, *back.next().unwrap());
while f + b != target {
if f + b > target {
b = *back.next().unwrap();
b_idx -= 1;
} else {
f = *front.next().unwrap();
f_idx += 1;
}
}
vec![f_idx, b_idx]
}
}