本文主要是介绍leetcode - 303. Range Sum Query - Immutable 【动态规划 + 间接逼近目标 + 区间计算 +刻度 + 距离计算方式 】,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
题目
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.
分析及解答
目标:是 方便计算任意一个区间的距离。
导出的目标: 以 起始点为基准点,然后使得 区间的计算可以归结为距离的相减。
1.修改原数组
class NumArray {int[] nums;public NumArray(int[] nums) {for(int i = 1; i < nums.length; i++)nums[i] += nums[i - 1];this.nums = nums;
}public int sumRange(int i, int j) {if(i == 0)return nums[j];return nums[j] - nums[i - 1];
}}/*** Your NumArray object will be instantiated and called as such:* NumArray obj = new NumArray(nums);* int param_1 = obj.sumRange(i,j);*/
2.不修改原数组
public class NumArray {int[] dp;public NumArray(int[] nums) {int len = nums.length;dp = new int[len+1];dp[0] = 0;for(int i = 1; i<=len; i++){dp[i] = dp[i-1] + nums[i-1];}}public int sumRange(int i, int j) {return dp[j+1]-dp[i];}
}
这篇关于leetcode - 303. Range Sum Query - Immutable 【动态规划 + 间接逼近目标 + 区间计算 +刻度 + 距离计算方式 】的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!