LeetCode上的题目 "303. 区域和检索 - 数组不可变",是一个相对简单的问题。
问题描述:
给定一个整数数组 nums,求出该数组从索引 i 到 j(i ≤ j)范围内元素的总和,包含 i, j 两点。
实现 NumArray 类:
NumArray(int[] nums) 用整数数组 nums 初始化对象
int sumRange(int i, int j) 返回数组 nums 从索引 i 到 j(i ≤ j)范围内元素的总和,包含 i, j 两点(也就是 sum(nums[i], nums[i + 1], ... , nums[j]))
示例:
输入:
nums = [-2, 0, 3, -5, 2, -1]
sumRange(0, 2) -> 1
sumRange(2, 5) -> -1
sumRange(0, 5) -> -3
思路:利用前缀和或者dp 记录,从头开始每一步的累计和,然后在需要的时候直接取值
//leetcode submit region begin(Prohibit modification and deletion)
class NumArray {
private int[] prefixNum;
public NumArray(int[] nums) {
prefixNum = new int[nums.length];
prefixNum[0]=nums[0];
for (int i = 1; i < nums.length; i++) {
prefixNum[i]= prefixNum[i-1]+nums[i];
}
}
public int sumRange(int left, int right) {
if(left == 0){
return prefixNum[right];
}
return prefixNum[right]-prefixNum[left-1];
}
}
/**
* Your NumArray object will be instantiated and called as such:
* NumArray obj = new NumArray(nums);
* int param_1 = obj.sumRange(left,right);
*/
//leetcode submit region end(Prohibit modification and deletion)
标签:right,leetcode303,前缀,NumArray,int,nums,prefixNum,sumRange
From: https://www.cnblogs.com/xiaoshahai/p/17291794.html