标签:
1、题目名称
Range Sum Query(数组指定区间内的元素和)
2、题目地址
https://leetcode.com/problems/range-sum-query-immutable/
3、题目内容
英文:Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive.
中文:给定一个数组nums,求出索引i和j之间元素的和,i一定是小于或等于j的
例如:
Given nums = [-2, 0, 3, -5, 2, -1] sumRange(0, 2) -> 1 sumRange(2, 5) -> -1 sumRange(0, 5) -> -3
注意:你可以假定数组不会发生变化,sumRange函数会被调用多次
4、解题方法1
不同于其他题目以Solution为类名,本题中给出的类名为NumArray,并且里面有两个函数。第一个函数为构造函数,第二个函数为sumRange,这两个函数都是我们要实现的函数。
题目给出的代码结构如下:
public class NumArray {
public NumArray(int[] nums) {
}
public int sumRange(int i, int j) {
}
}
// Your NumArray object will be instantiated and called as such:
// NumArray numArray = new NumArray(nums);
// numArray.sumRange(0, 1);
// numArray.sumRange(1, 2);
在本题中,sumRange可能会被调用多次,因此采用下面这种方式是不明智的(会导致TLE):
public class NumArray {
public int[] nums;
public NumArray(int[] nums) {
this.nums = nums;
}
public int sumRange(int i, int j) {
int result = 0;
for (int counter = i; counter <= j; counter++) {
result += nums[counter];
}
return result;
}
}
如果我们换一种思路,在构造函数内就计算了从第一个元素到当前元素所有元素的和,保存到数组sums的对应位置中,在函数sumRange中就可以很方便地算出题目中要求的结果了。
Java代码如下:
/**
* @功能说明:LeetCode 303 - Range Sum Query - Immutable
* @开发人员:Tsybius2014
* @开发时间:2015年11月10日
*/
public class NumArray {
public int[] sums;
public NumArray(int[] nums) {
if (nums == null) {
sums = null;
} else if (nums.length == 0) {
sums = new int[0];
} else {
this.sums = new int[nums.length];
sums[0] = nums[0];
for (int i = 1; i < nums.length; i++) {
sums[i] = sums[i - 1] + nums[i];
}
}
}
public int sumRange(int i, int j) {
if (i >= sums.length || j >= sums.length || i > j) {
return 0;
} else if (i == 0) {
return sums[j];
} else {
return sums[j] - sums[i - 1];
}
}
}
END
LeetCode:Range Sum Query - Immutable - 数组指定区间内的元素和
标签:
原文地址:http://my.oschina.net/Tsybius2014/blog/528708