动态规划---范围累加和查询

1、题目

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

2、解答:累加和,注意向量的作用域


3、代码

C++代码

class NumArray {
public:
    vector<int> num;
    NumArray(vector<int> nums) {
        for(int i=1;i<nums.size();i++)
            nums[i] += nums[i-1];
        num = nums;
    }
   
    int sumRange(int i, int j) {
        if(i==0)
            return num[j];
        return num[j] - num[i-1];
    }

};

python代码

class NumArray:

    def __init__(self, nums):
        """
        :type nums: List[int]
        """
        self.nums = nums
        

    def sumRange(self, i, j):
        """
        :type i: int
        :type j: int
        :rtype: int
        """
        return sum(self.nums[i:j+1])


猜你喜欢

转载自blog.csdn.net/qq_31307013/article/details/80576391