303. Range Sum Query - Immutable
求数组中任意两个数之间所有数字的和- Total Accepted: 37248
- Total Submissions: 146945
- Difficulty: Easy
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
Note:
- You may assume that the array does not change.
- There are many calls to sumRange function.
Subscribe to see which companies asked this question
1 // 存储数组的结构体 2 struct NumArray { 3 int num; 4 int sum; 5 }; 6 7 /** Initialize your data structure here. */ 8 struct NumArray* NumArrayCreate(int* nums, int numsSize) { 9 int i = 0; 10 struct NumArray *NumArr = (struct NumArray*)malloc(sizeof(struct NumArray)*numsSize);//数组结构体初始化 11 struct NumArray* p = NumArr; 12 13 //非空数组 14 if(numsSize == 0) 15 return NULL; 16 17 //初始化第一个元素 18 p[0].num = nums[0]; 19 p[0].sum = nums[0]; 20 i++; 21 while(i < numsSize){ 22 p[i].num = nums[i]; 23 p[i].sum = p[i-1].sum + nums[i]; 24 i++; 25 } 26 27 return NumArr; 28 } 29 30 int sumRange(struct NumArray* numArray, int i, int j) { 31 //sum[j] -sum[i] + num[i] 32 return (numArray[j].sum - numArray[i].sum + numArray[i].num); 33 } 34 35 /** Deallocates memory previously allocated for the data structure. */ 36 void NumArrayFree(struct NumArray* numArray) { 37 free(numArray); 38 } 39 40 // Your NumArray object will be instantiated and called as such: 41 // struct NumArray* numArray = NumArrayCreate(nums, numsSize); 42 // sumRange(numArray, 0, 1); 43 // sumRange(numArray, 1, 2); 44 // NumArrayFree(numArray);