A daily programming problem
Title Description
Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive.
Title effect: Given an array of numbers, wherein the calculation of the standard element from i to j, and, i, j They are legitimate and is closed interval.
Sample
Example:
Given nums = [-2, 0, 3, -5, 2, -1]
sumRange(0, 2) -> 1
sumRange(2, 5) -> -1
sumRange(0, 5) -> -3
python Solution
class NumArray:
def __init__(self, nums: List[int]):
self.nums = []
for i,n in enumerate(nums):
if i != 0:
self.nums.append(self.nums[i-1]+n)
else:
self.nums.append(n)
def sumRange(self, i: int, j: int) -> int:
return self.nums[j] - (i and self.nums[i-1])
Runtime: 96 ms, faster than 54.19% of Python3 online submissions for Range Sum Query - Immutable.
Memory Usage: 17.3 MB, less than 10.00% of Python3 online submissions for Range Sum Query - Immutable.
题后反思:
- This simple idea is subject directly nums assigned to an instance variable, and the range given is added directly, but this approach virtually duplicate calculations many times.
- Therefore, in order to improve the algorithm, it may in fact be a list of position to the current position and calculate at initialization time, do a subtraction in the calculation of direct and a range on it.
- Because of the demand interval is closed and the elements, so in the time scale of the subtraction element i is determined whether the required bounds.
C language Solution
typedef struct {
int *data;
} NumArray;
NumArray* numArrayCreate(int* nums, int numsSize) {
NumArray* num = (NumArray*)malloc(sizeof(NumArray));
num -> data = (int*)malloc(sizeof(int)*(numsSize+1));
num -> data[0] = 0;
for (int i=1;i<=numsSize;i++)
{
num -> data[i] = num -> data[i-1] + nums[i-1];
}
return num;
}
int numArraySumRange(NumArray* obj, int i, int j) {
return obj->data[j+1] - obj->data[i];
}
void numArrayFree(NumArray* obj) {
free(obj->data);
free(obj);
}
Runtime: 24 ms, faster than 72.22% of C online submissions for Range Sum Query - Immutable.
Memory Usage: 12.5 MB, less than 33.33% of C online submissions for Range Sum Query - Immutable.
题后反思:
- C multi-language solution applied for a space to store a 0, thus ensuring the j + 1 is not out of bounds (at i, j are legally permissible)
This paper is my personal understanding, if the wrong place welcome comments below tell me, I promptly corrected, common progress