mirror of
https://gitlab.com/mfocko/LeetCode.git
synced 2024-11-10 00:09:06 +01:00
problems(rs): add “303. Range Sum Query - Immutable”
Signed-off-by: Matej Focko <mfocko@redhat.com>
This commit is contained in:
parent
09a14a0e3d
commit
43d043b5e1
1 changed files with 45 additions and 0 deletions
45
problems/range-sum-query-immutable.rs
Normal file
45
problems/range-sum-query-immutable.rs
Normal file
|
@ -0,0 +1,45 @@
|
|||
#[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);
|
||||
}
|
||||
}
|
Loading…
Reference in a new issue