zipping iterators is slower but uses less memory.

This commit is contained in:
Joe Ardent 2024-05-15 12:44:37 -07:00
parent edbe0571dc
commit 319fed1511

View file

@ -1,5 +1,5 @@
fn main() {
println!("Hello, world!");
dbg!(f(vec![2, 1, -1]));
}
fn f(nums: Vec<i32>) -> i32 {
@ -9,12 +9,11 @@ fn f(nums: Vec<i32>) -> i32 {
cur += n;
rights.push(cur);
}
rights.reverse();
let rights = &rights;
cur = 0;
for (i, num) in nums.into_iter().enumerate() {
cur += num;
if cur == rights[i] {
for (i, (left, &right)) in nums.iter().zip(rights.iter().rev()).enumerate() {
cur += left;
if cur == right {
return i as i32;
}
}