|
| 1 | +/** |
| 2 | + * [303] Range Sum Query - Immutable |
| 3 | + * |
| 4 | + * Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive. |
| 5 | + * |
| 6 | + * Example:<br> |
| 7 | + * |
| 8 | + * Given nums = [-2, 0, 3, -5, 2, -1] |
| 9 | + * |
| 10 | + * sumRange(0, 2) -> 1 |
| 11 | + * sumRange(2, 5) -> -1 |
| 12 | + * sumRange(0, 5) -> -3 |
| 13 | + * |
| 14 | + * |
| 15 | + * |
| 16 | + * Note:<br> |
| 17 | + * <ol> |
| 18 | + * You may assume that the array does not change. |
| 19 | + * There are many calls to sumRange function. |
| 20 | + * </ol> |
| 21 | + * |
| 22 | + */ |
| 23 | +pub struct Solution {} |
| 24 | + |
| 25 | +// submission codes start here |
| 26 | + |
| 27 | +struct NumArray { |
| 28 | + nums: Vec<i32>, |
| 29 | +} |
| 30 | + |
| 31 | +/** |
| 32 | + * `&self` means the method takes an immutable reference. |
| 33 | + * If you need a mutable reference, change it to `&mut self` instead. |
| 34 | + */ |
| 35 | +impl NumArray { |
| 36 | + fn new(nums: Vec<i32>) -> Self { |
| 37 | + let mut res = 0; |
| 38 | + let mut vec = Vec::with_capacity(nums.len()); |
| 39 | + for &num in nums.iter() { |
| 40 | + res += num; |
| 41 | + vec.push(res); |
| 42 | + } |
| 43 | + NumArray{nums: vec} |
| 44 | + } |
| 45 | + |
| 46 | + fn sum_range(&self, i: i32, j: i32) -> i32 { |
| 47 | + let (i, j) = (i as usize, j as usize); |
| 48 | + self.nums[j] - if i > 0 { self.nums[i-1] } else { 0 } |
| 49 | + } |
| 50 | +} |
| 51 | + |
| 52 | +/** |
| 53 | + * Your NumArray object will be instantiated and called as such: |
| 54 | + * let obj = NumArray::new(nums); |
| 55 | + * let ret_1: i32 = obj.sum_range(i, j); |
| 56 | + */ |
| 57 | + |
| 58 | +// submission codes end |
| 59 | + |
| 60 | +#[cfg(test)] |
| 61 | +mod tests { |
| 62 | + use super::*; |
| 63 | + |
| 64 | + #[test] |
| 65 | + fn test_303() { |
| 66 | + let mut nums = NumArray::new(vec![-2, 0, 3, -5, 2, -1]); |
| 67 | + assert_eq!(nums.sum_range(0, 2), 1); |
| 68 | + assert_eq!(nums.sum_range(2, 5), -1); |
| 69 | + assert_eq!(nums.sum_range(0, 5), -3); |
| 70 | + } |
| 71 | +} |
0 commit comments