本文主要是介绍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:
思路:他给了两个函数:第一个遍历时顺带把array[i]变为前i个的和,这样计算时做个减法就行了
class NumArray {//思路,在NumArray中求出每个索引对应的前n个的和,这样最后求值只只要做个减法就行了vector<int> myNum;
public:NumArray(vector<int> &nums) {for(int i=1;i<nums.size();i++){nums[i] = nums[i-1]+nums[i];}myNum = nums;}int sumRange(int i, int j) {//保证j>=iif(i == 0){return myNum[j];}return myNum[j] - myNum[i-1];}
};// Your NumArray object will be instantiated and called as such:
// NumArray numArray(nums);
// numArray.sumRange(0, 1);
// numArray.sumRange(1, 2);
这篇关于leetcode-303. Range Sum Query - Immutable的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!