303.Range Sum Query Immutable - LeetCode

?题目描述

给定一个整数数组  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 方法。

 ?Method 1: 没有做任何pre-processing,先query后计算sum.    Note:Time:O(m*n),Space:O(n)

class NumArray {
public:
    NumArray(vector<int> nums) {
        nums_ = move(nums);
    }

    int sumRange(int i, int j) {
        int sum = 0;
        for (int k = i; k <= j; ++k) {
            sum += nums_[k];
        }
        return sum;
    }

private:
    vector<int> nums_;
};

/**
 * Your NumArray object will be instantiated and called as such:
 * NumArray obj = new NumArray(nums);
 * int param_1 = obj.sumRange(i,j);
 */

 ?Method 2:dynamic programming进行一个pre-processing.Note:Time:O(m+n),Space:O(n)),动态规划,注意找到状态的转化方程式。

  

//动态规划,注意找到状态的转化方程式
class NumArray {
public:
    NumArray(vector<int> nums) {
        int n = nums.size();
        if(n==0) return;//当时没写这一句,直接报错。以后记得defensive programming
        sum_ = vector<int>(n, 0);
        sum_[0] = nums[0];
        for (int i = 1; i < n; ++i) {
            sum_[i] = sum_[i - 1] + nums[i];
        }
    }

    int sumRange(int i, int j) {
        if (i==0) { return sum_[j]; }
        return sum_[j] - sum_[i - 1];
    }
private:
    vector<int> sum_;
};

/**
 * Your NumArray object will be instantiated and called as such:
 * NumArray obj = new NumArray(nums);
 * int param_1 = obj.sumRange(i,j);
 */

  ?知识点

int main()
{
    std::string str = "Hello";
    std::vector<std::string> v;
    //调用常规的拷贝构造函数,新建字符数组,拷贝数据
    v.push_back(str);
    std::cout << "After copy, str is \"" << str << "\"\n";
    //调用移动构造函数,掏空str,掏空后,最好不要使用str
    v.push_back(std::move(str));
    std::cout << "After move, str is \"" << str << "\"\n";
    std::cout << "The contents of the vector are \"" << v[0]
              << "\", \"" << v[1] << "\"\n";
}


>>After copy, str is "Hello"
>>After move, str is ""
>>The contents of the vector are "Hello", "Hello"

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值