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