Skip to content

Commit 202f6a6

Browse files
committed
Create 0303-range-sum-query-immutable.swift
1 parent d642910 commit 202f6a6

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
/**
2+
* Question Link: https://leetcode.com/problems/range-sum-query-immutable/
3+
*/
4+
5+
6+
class NumArray {
7+
var pref: [Int]
8+
9+
init(_ nums: [Int]) {
10+
pref = []
11+
var total = 0
12+
for n in nums {
13+
total += n
14+
pref.append(total)
15+
}
16+
}
17+
18+
func sumRange(_ left: Int, _ right: Int) -> Int {
19+
let prefRight = pref[right]
20+
let prefLeft = left > 0 ? pref[left - 1] : 0
21+
return (prefRight - prefLeft)
22+
}
23+
}
24+
25+
/**
26+
* Your NumArray object will be instantiated and called as such:
27+
* let obj = NumArray(nums)
28+
* let ret_1: Int = obj.sumRange(left, right)
29+
*/

0 commit comments

Comments
 (0)