zl程序教程

您现在的位置是:首页 >  其他

当前栏目

[LeetCode] Range Sum Query - Immutable

LeetCode Query sum range Immutable
2023-09-14 09:01:04 时间
Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive. Example:

Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive.

Example:


You may assume that the array does not change. There are many calls to sumRange function.

考虑到要多次调用sumRange()函数,因此需要把结果先存起来,调用时就可以直接返回了。最开始考虑的是用dp[i][j]来直接存储i到j之间元素的和,但是内存超出限制。于是考虑用dp[i]来存储0到i之间元素的和,0到j的和减去0到i-1的和即为所求。

// Runtime: 3 ms

public class NumArray {

 private int[] dp;

 public NumArray(int[] nums) {

 dp = new int[nums.length];

 int sum = 0;

 for (int i = 0; i nums.length; i++) {

 sum += nums[i];

 dp[i] = sum;

 public int sumRange(int i, int j) {

 return i == 0 ? dp[j] : dp[j] - dp[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);

Lazy Join Optimizations Without Upfront Statistics 立即下载