letecode [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:
Given nums = [-2, 0, 3, -5, 2, -1] sumRange(0, 2) -> 1 sumRange(2, 5) -> -1 sumRange(0, 5) -> -3
Note:
- You may assume that the array does not change.
- There are many calls to sumRange function.
题目大意:
给定一个整数数组,计算下标i 到 j的元素和。
理 解:
方法一:直观解法
定义私有成员vector数组,声明类对象时初始化数组;调用求和函数时计算m_num[i] + ... + m_nums[j]的值。
方法二:多次调用求和接口函数
定义私有成员vector数组,由于要多次调用求和接口,vector数组第i个元素表示初始化参数数组[0到i的和];则求和 = m_num[j+1] - m_num[i-1]。
代 码 C++:
方法一:
class NumArray { private: vector<int> m_nums; public: NumArray(vector<int>& nums) { for(int v:nums){ m_nums.push_back(v); } } int sumRange(int i, int j) { int sum = 0; while(i<=j){ sum += m_nums[i]; i++; } return sum; } }; /** * Your NumArray object will be instantiated and called as such: * NumArray* obj = new NumArray(nums); * int param_1 = obj->sumRange(i,j); */
方法二:
class NumArray { private: vector<int> m_nums; public: NumArray(vector<int>& nums) { if(nums.size()>0){ m_nums.push_back(nums[0]); for(int i=1;i<nums.size();++i){ m_nums.push_back(m_nums[i-1] + nums[i]); } } } int sumRange(int i, int j) { if(i==0) return m_nums[j]; else return m_nums[j]-m_nums[i-1]; } }; /** * Your NumArray object will be instantiated and called as such: * NumArray* obj = new NumArray(nums); * int param_1 = obj->sumRange(i,j); */
运行结果:
方法一:
执行用时 :448 ms, 在所有C++提交中击败了6.87%的用户
内存消耗 :17.4 MB, 在所有C++提交中击败了10.40%的用户
方法二:
执行用时 :36 ms, 在所有C++提交中击败了98.43%的用户
内存消耗 :17.2 MB, 在所有C++提交中击败了59.24%的用户