您的位置:首页 > 产品设计 > UI/UE

LeetCode_Range Sum Query - Immutable

2015-11-13 20:19 369 查看
Given an integer array nums, find the sum of the elements between indicesi 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.
解题思路:此题从字面上看并不难,只要找出数组中对应索引位置,并计算从0-index的和并做对应索引的减法即可,但是注意题目中的Note可以发现,你的方法可能会被大量的调用,所以每次调用都去做运算是不合适的,必将出现Time Limited Exceeded。所以需要在类构造时,便需要准备一些结果集(所有索引到0的和),以便在后面的运算中减少计算量。

public class NumArray {
private int[] mArr = null;
private int[] mResults = null;

// 3ms
public NumArray(int[] nums) {
mArr = nums;
mResults = new int[mArr.length];
for (int i = 0; i < mArr.length; i++) {
if (i == 0) {
mResults[0] = mArr[0];
} else {
mResults[i] = mResults[i - 1] + mArr[i];
}
}
}

public int sumRange(int i, int j) {
if (mArr == null || mArr.length - 1 < i || mArr.length - 1 < j || i < 0
|| j < 0) {
return 0;
}
int result = i <= 0 ? mResults[j] : (mResults[j] - mResults[i - 1]);
return result;
}

public static void main(String[] args) {
int[] nums = { -2, 0, 3, -5, 2, -1 };
// sumRange(0, 2) -> 1
// sumRange(2, 5) -> -1
// sumRange(0, 5) -> -3
NumArray numArray = new NumArray(nums);
numArray.sumRange(0, 2);
numArray.sumRange(2, 5);
numArray.sumRange(0, 5);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: