先说坑!:
结果输出:
数组名40
指针4
在函数中4
sizeof区别!!注意!!!出处:http://blog.csdn.net/kangroger/article/details/20653255
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.
一下子不知道如何下手了,看网上说 可以先求出sum[i],前i个的和存储起来再相减!代码如下:
class NumArray {
public:
int* sum;
int size;
NumArray(vector<int> nums) {
size = nums.size();
if (size == 0)
return ;
sum = new int[size];
sum[0] = nums[0];
for (int i = 1 ; i < size ; i ++)
sum[i] = sum[i - 1] + nums[i];
}
int sumRange(int i, int j) {
int length = sizeof(sum);
if(size == 0 || i > size || j > size || i > j)
return 0;
if(i == 0)
return sum[j];
else
return sum[j] - sum[i-1];
}
};
/**
* Your NumArray object will be instantiated and called as such:
* NumArray obj = new NumArray(nums);
* int param_1 = obj.sumRange(i,j);
*/
还是踩了sizeof的坑~注意啊指的是指针大小而不是数组元素个数!