美文网首页Leetcode
Leetcode 303. Range Sum Query -

Leetcode 303. Range Sum Query -

作者: SnailTyan | 来源:发表于2019-02-18 17:56 被阅读2次

    文章作者: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);
     */![Screen Shot 2019-02-18 at 17.21.44.png](https://img.haomeiwen.com/i3232548/929965674bc9107d.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
    
    

    Reference

    1. https://leetcode.com/problems/range-sum-query-immutable/description/

    相关文章

      网友评论

        本文标题:Leetcode 303. Range Sum Query -

        本文链接:https://www.haomeiwen.com/subject/wdhzeqtx.html