8000 src/bin/range-sum-query-immutable.rs · bestgopher/leetcode@a2aea48 · GitHub
[go: up one dir, main page]

Skip to content

Commit a2aea48

Browse files
committed
src/bin/range-sum-query-immutable.rs
1 parent 22845f5 commit a2aea48

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

src/bin/range-sum-query-immutable.rs

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
fn main() {}
2+
3+
struct Solution;
4+
5+
6+
/**
7+
* Your NumArray object will be instantiated and called as such:
8+
* let obj = NumArray::new(nums);
9+
* let ret_1: i32 = obj.sum_range(left, right);
10+
*/
11+
struct NumArray {
12+
sums: Vec<i32>
13+
}
14+
15+
16+
/**
17+
* `&self` means the method takes an immutable reference.
18+
* If you need a mutable reference, change it to `&mut self` instead.
19+
*/
20+
impl NumArray {
21+
fn new(nums: Vec<i32>) -> Self {
22+
let mut sums = Vec::with_capacity(nums.len());
23+
24+
for i in 0..=nums.len() {
25+
if i == 0 {
26+
sums.push(0);
27+
} else {
28+
sums.push(nums[i] + sums[i - 1]);
29+
}
30+
}
31+
32+
Self { sums }
33+
}
34+
35+
fn sum_range(&self, left: i32, right: i32) -> i32 {
36+
if left == 0 {
37+
self.sums[right as usize]
38+
} else {
39+
self.sums[right as usize] - self.sums[left as usize - 1usize]
40+
}
41+
}
42+
}

0 commit comments

Comments
 (0)
0