LeetCode/problems/range-sum-query-immutable.rs
Matej Focko 43d043b5e1
problems(rs): add “303. Range Sum Query - Immutable”
Signed-off-by: Matej Focko <mfocko@redhat.com>
2023-04-16 00:05:53 +02:00

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);
}
}