From 691a3e0bb22d4f87c02261472cfd598cb8a8caa4 Mon Sep 17 00:00:00 2001 From: jackfiled Date: Mon, 18 Mar 2024 10:50:21 +0800 Subject: [PATCH] 20240318 Finished --- src/problem/mod.rs | 3 +- src/problem/p303_range_sum_query_immutable.rs | 57 +++++++++++++++++++ 2 files changed, 59 insertions(+), 1 deletion(-) create mode 100644 src/problem/p303_range_sum_query_immutable.rs diff --git a/src/problem/mod.rs b/src/problem/mod.rs index 71bdf72..b432d61 100644 --- a/src/problem/mod.rs +++ b/src/problem/mod.rs @@ -76,4 +76,5 @@ mod p2864_maximum_odd_binary_number; mod p2789_largest_element_in_an_array_after_merge_operations; mod p2312_selling_pieces_of_wood; mod p2684_maximum_number_of_moves_in_a_grid; -mod p310_minimum_height_trees; \ No newline at end of file +mod p310_minimum_height_trees; +mod p303_range_sum_query_immutable; \ No newline at end of file diff --git a/src/problem/p303_range_sum_query_immutable.rs b/src/problem/p303_range_sum_query_immutable.rs new file mode 100644 index 0000000..1ab25bc --- /dev/null +++ b/src/problem/p303_range_sum_query_immutable.rs @@ -0,0 +1,57 @@ +/** + * [303] Range Sum Query - Immutable + */ +pub struct Solution {} + +// submission codes start here + +struct NumArray { + prefix_array: Vec, +} + +/** + * `&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) -> 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() {} +}