soapyigu/LeetCode-Swift

[Solution] 303. Range Sum Query - Immutable

iosconstantine opened this issue · 0 comments

/**

*/

class NumArray {
	var sums: [Int] = []

	init(_ nums: [Int]) {
		var currentSum = 0

		for num in nums {
			currentSum += num
			sums.append(currentSum)
		}
		print(sums)
	}

	func sumRange(_ left: Int, _ right: Int) -> Int {
		if left == 0 {
			return sums[right]
		}
		return sums[right] - sums[left-1]
	}
}