Leetcode 303. Range Sum Query - Immutable

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. Description

Range Sum Query - Immutable

2. Solution

  • Version 1
class NumArray {
public:
    NumArray(vector<int> nums) {
        this->nums = nums;
    }
    
    int sumRange(int i, int j) {
        int sum = 0;
        for(int index = i; index <= j; index++) {
            sum += nums[index];
        }
        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);
 */
  • Version 2
class NumArray {
public:
    NumArray(vector<int> nums) {
        int sum = 0;
        for(int num: nums) {
            sum += num;
            sums.push_back(sum);
        }
    }
    
    int sumRange(int i, int j) {
        if(i > 0) {
            return sums[j] - sums[i - 1];
        }
        return sums[j];
    }

private:
    vector<int> sums;
};

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

Reference

  1. https://leetcode.com/problems/range-sum-query-immutable/description/
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容