# 303. 区域和检索 - 不可变

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.

sumRange(0, 2) -> 1
sumRange(2, 5) -> -1
sumRange(0, 5) -> -3

class NumArray {

int[] arr;
public NumArray(int[] nums) {
arr = new int[nums.length];
for(int i=0;i<nums.length;i++){
arr[i] = nums[i];
}
}

public int sumRange(int i, int j) {
int res = 0;
for(int t=i;t<=j;t++){
res += arr[t];
}
return res;
}
}

/**
* Your NumArray object will be instantiated and called as such:
* NumArray obj = new NumArray(nums);
* int param_1 = obj.sumRange(i,j);
*/

class NumArray {

int[] arr;
public NumArray(int[] nums) {
arr = Arrays.copyOf(nums,nums.length);
}

public int sumRange(int i, int j) {
int res = 0;
for(int t=i;t<=j;t++){
res += arr[t];
}
return res;
}
}

/**
* Your NumArray object will be instantiated and called as such:
* NumArray obj = new NumArray(nums);
* int param_1 = obj.sumRange(i,j);
*/

3、第三次代码：

class NumArray {

int[][] arr;
public NumArray(int[] nums) {
arr = new int[nums.length][nums.length];
for(int i=0;i<nums.length;i++){
arr[i][i] = nums[i];
for(int j=i+1;j<nums.length;j++){
arr[i][j] = arr[i][j-1] + nums[j];
}
}

}

public int sumRange(int i, int j) {
return arr[i][j];
}
}

class NumArray {

int[] arr;
public NumArray(int[] nums) {
arr = new int[nums.length];
if(nums.length > 0){
arr[0] = nums[0];
for(int i=1;i<nums.length;i++){
arr[i] = arr[i-1] + nums[i];
}
}

}

public int sumRange(int i, int j) {
if(i == 0)
return arr[j];
else
return arr[j] - arr[i-1];
}
}

• 广告
• 抄袭
• 版权
• 政治
• 色情
• 无意义
• 其他

120