20240318 Finished

This commit is contained in:
jackfiled 2024-03-18 10:50:21 +08:00
parent bf7033033a
commit 691a3e0bb2
2 changed files with 59 additions and 1 deletions

View File

@ -77,3 +77,4 @@ mod p2789_largest_element_in_an_array_after_merge_operations;
mod p2312_selling_pieces_of_wood; mod p2312_selling_pieces_of_wood;
mod p2684_maximum_number_of_moves_in_a_grid; mod p2684_maximum_number_of_moves_in_a_grid;
mod p310_minimum_height_trees; mod p310_minimum_height_trees;
mod p303_range_sum_query_immutable;

View File

@ -0,0 +1,57 @@
/**
* [303] Range Sum Query - Immutable
*/
pub struct Solution {}
// submission codes start here
struct NumArray {
prefix_array: Vec<i32>,
}
/**
* `&self` means the method takes an immutable reference.
* If you need a mutable reference, change it to `&mut self` instead.
*/
impl NumArray {
fn new(nums: Vec<i32>) -> Self {
let mut prefix_array = Vec::with_capacity(nums.len());
for (index, value) in nums.iter().enumerate() {
if index == 0 {
prefix_array.push(*value);
} else {
prefix_array.push(prefix_array[index - 1] + *value);
}
}
NumArray { prefix_array }
}
fn sum_range(&self, left: i32, right: i32) -> i32 {
let left = left as usize;
let right = right as usize;
return if left == 0 {
self.prefix_array[right]
} else {
self.prefix_array[right] - self.prefix_array[left - 1]
};
}
}
/**
* Your NumArray object will be instantiated and called as such:
* let obj = NumArray::new(nums);
* let ret_1: i32 = obj.sum_range(left, right);
*/
// submission codes end
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_303() {}
}