# 3ms java solution, with array, no special i==0 check

• ``````public class NumArray {
// 7:54pm - 8:01pm
private int[] nums;
private int[] sums;

public NumArray(int[] nums) {
this.nums = nums;
if (nums == null) {
return;
}
sums = new int[nums.length+1];
sums[0] = 0;
for (int i=1; i<=nums.length; i++) {
sums[i] = sums[i-1] + nums[i-1];
}
}

public int sumRange(int i, int j) {
return sums[j+1] - sums[i];
}
}``````

• why java is fast than c++?

my two c++ codes are just like yours, and both of them are 584ms..

``````class NumArray {
public:
NumArray(vector<int> &nums) {
sums.push_back(0);
for(int i = 0; i < nums.size(); i++)
sums.push_back(sums.back() + nums[i]);
}

int sumRange(int i, int j) {
return sums[j + 1] - sums[i];
}

private:
vector<int> sums;
};

class NumArray {
public:
NumArray(vector<int> &nums) {
sums = new int[nums.size() + 1];
sums[0] = 0;
for(int i = 0; i < nums.size(); i++)
sums[i + 1] = sums[i] + nums[i];
}

int sumRange(int i, int j) {
return sums[j + 1] - sums[i];
}

private:
int *sums;
};
``````

• maybe because I used array? I don't know c++ well so I don't know the details of vector. Do you think maybe you can use a fixed-size array

• my second code uses dynamic array,but it also runs 584ms...

• There is still an error in your code.The for cycle should be
for (int i=1; i<=nums.length+1; i++) {
sums[i] = sums[i-1] + nums[i-1];
}

• did you test it? i think you will get a array index out of bound error.

• Not really.I submitted my code and it has been accepted.Think about that,when i=nums.length+1,it will jump out the cycle.So the last executed i is i=nums.length,then nums[i-1] won't out of bound.

• i resubmitted my code and it was accepted. maybe you can copy and paste my code and submit it yourself.

• My solution is the same as you.

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.