- 最开始简单的思路。。。超时了
class NumArray { public: NumArray(vector<int> &nums) { num = nums; } int sumRange(int i, int j) { int sum = 0; for (int x = i;x<j+1;x++) { sum = sum +num[x]; } return sum; } private: vector <int> num; };
- 更换思路,在构造函数里计算每个元素之前所有元素的和,然后用j的与i的做差即可
class NumArray { public: NumArray(vector<int> &nums) { if (nums.size()>0) { sum = new int[nums.size()]; sum[0] = nums[0]; for (int i = 1;i<nums.size();i++) { sum[i] = sum[i-1]+nums[i]; } } } int sumRange(int i, int j) { if (i!=0) { return sum[j]-sum[i-1]; } else { return sum[j]; } } private: int *sum; };
Leetcode 303. Range Sum Query - Immutabled
最新推荐文章于 2024-08-07 08:23:35 发布