LeetCode/rs/find-pivot-index.rs

21 lines
420 B
Rust
Raw Permalink Normal View History

2022-07-12 14:36:28 +02:00
use std::convert::TryInto;
impl Solution {
2022-07-12 14:36:28 +02:00
pub fn pivot_index(nums: Vec<i32>) -> i32 {
let mut from_left: i32 = 0;
let mut from_right: i32 = nums.iter().sum();
2022-07-12 14:36:28 +02:00
for (i, e) in nums.iter().enumerate() {
from_right -= e;
2022-07-12 14:36:28 +02:00
if from_left == from_right {
return i.try_into().unwrap();
}
2022-07-12 14:36:28 +02:00
from_left += e;
}
2022-07-12 14:36:28 +02:00
-1
}
}