mirror of
https://gitlab.com/mfocko/LeetCode.git
synced 2024-11-10 00:09:06 +01:00
45 lines
957 B
Rust
45 lines
957 B
Rust
#[derive(Debug)]
|
|
struct NumArray {
|
|
prefix_sums: Vec<i32>,
|
|
}
|
|
|
|
impl NumArray {
|
|
fn new(nums: Vec<i32>) -> Self {
|
|
let mut total = nums.iter().sum::<i32>();
|
|
|
|
let mut prefix_sums: Vec<i32> = nums
|
|
.iter()
|
|
.scan(total, |total, &x| {
|
|
let prev = *total;
|
|
*total -= x;
|
|
|
|
Some(prev)
|
|
})
|
|
.collect();
|
|
prefix_sums.push(0);
|
|
|
|
Self { prefix_sums }
|
|
}
|
|
|
|
fn sum_range(&self, left: i32, right: i32) -> i32 {
|
|
self.prefix_sums[left as usize] - self.prefix_sums[right as usize + 1]
|
|
}
|
|
}
|
|
|
|
fn main() {}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
#[test]
|
|
fn example_1() {
|
|
let num_arr = NumArray::new(vec![-2, 0, 3, -5, 2, -1]);
|
|
|
|
dbg!("{:?}", &num_arr);
|
|
|
|
assert_eq!(num_arr.sum_range(0, 2), 1);
|
|
assert_eq!(num_arr.sum_range(2, 5), -1);
|
|
assert_eq!(num_arr.sum_range(0, 5), -3);
|
|
}
|
|
}
|