geQuestion:
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.
Analysis:
给出一个整数数组,得出i与j之间的数字之和(i<=j)。你可以假设数组不会改变,并且他们可以调用多次sunRange函数。
Answer:
解法一:
public class NumArray { int[] num; public NumArray(int[] nums) { this.num = nums; } public int sumRange(int i, int j) { int res = 0; for(int k=i; k<j+1; k++) { res += num[k]; } return res; } } // Your NumArray object will be instantiated and called as such: // NumArray numArray = new NumArray(nums); // numArray.sumRange(0, 1); // numArray.sumRange(1, 2);
解法二:由于题目中说会多次调用该函数,计算某个区间内的和,如果按照上面的解法,当数组过大时,会导致多次重复计算和,因此我们可以想办法存储中间计算的结果来简化计算。 方法就是一次存储从第0个元素到第i个元素计算的中间结果,当求某个区间的和时,直接用大区间减去小区间的和即可。
public class NumArray { int[] num; public NumArray(int[] nums) { if(nums == null) num = null; else if(nums.length == 0) num = nums; else { num = new int[nums.length]; num[0] = nums[0]; for(int i=1; i<nums.length; i++) { num[i] = nums[i] + num[i-1]; } for(int i=0; i<num.length; i++) System.out.print(num[i] + " * "); System.out.println(); } } public int sumRange(int i, int j) { if(i == 0) return num[j]; else return num[j] - num[i-1]; } } // Your NumArray object will be instantiated and called as such: // NumArray numArray = new NumArray(nums); // numArray.sumRange(0, 1); // numArray.sumRange(1, 2);