LeetCode:区域和检索【303】
题目描述
给定一个整数数组 nums,求出数组从索引 i 到 j (i ≤ j) 范围内元素的总和,包含 i, j 两点。
示例:
给定 nums = [-2, 0, 3, -5, 2, -1],求和函数为 sumRange() sumRange(0, 2) -> 1 sumRange(2, 5) -> -1 sumRange(0, 5) -> -3
说明:
- 你可以假设数组不可变。
- 会多次调用 sumRange 方法。
题目分析
sums[i] = nums[0] + nums[1] + … + nums[i]
sumRange(i, j) = sums[j] – sums[i – 1]
Time complexity: pre-compute: O(n), query: O(1)
Space complexity: O(n)
Java题解
class NumArray { private int[] sums =null; public NumArray(int[] nums) { if(nums.length==0) return; sums = new int[nums.length]; sums[0]=nums[0]; for(int i=1;i<nums.length;i++) sums[i]=nums[i]+sums[i-1]; } public int sumRange(int i, int j) { if(i==0) return sums[j]; return sums[j]-sums[i-1]; } } /** * Your NumArray object will be instantiated and called as such: * NumArray obj = new NumArray(nums); * int param_1 = obj.sumRange(i,j); */