Leetcode - Range Sum Query - Immutable
https://leetcode.com/problems/range-sum-query-immutable/
Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive.
Example:
Given nums = [-2, 0, 3, -5, 2, -1] sumRange(0, 2) -> 1 sumRange(2, 5) -> -1 sumRange(0, 5) -> -3
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | type NumArray struct { sum [] int } func Constructor(nums [] int ) NumArray { if len(nums) == 0 { return NumArray{} } sum := make([] int , len(nums)) sum[0] = nums[0] for i := 1; i < len(nums); i++ { sum[i] = sum[i-1] + nums[i] } return NumArray{ sum: sum, } } func ( this *NumArray) SumRange(i int , j int ) int { if i == 0 { return this .sum[j] } return this .sum[j] - this .sum[i-1] } /** * Your NumArray object will be instantiated and called as such: * obj := Constructor(nums); * param_1 := obj.SumRange(i,j); */ |