publicclassNumArray{ privateint[] sum; publicNumArray(int[] nums){ if (nums != null && nums.length > 0) { sum = newint[nums.length]; int x = 0; for (int i = 0; i < nums.length; i++) { x += nums[i]; sum[i] = x; } } }
publicintsumRange(int i, int j){ if (sum == null || i > j || j >= sum.length) { return0; }
return sum[j] - (i > 0 ? sum[i - 1] : 0); } }
// Your NumArray object will be instantiated and called as such: // NumArray numArray = new NumArray(nums); // numArray.sumRange(0, 1); // numArray.sumRange(1, 2);