?题目描述
给定一个整数数组 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"