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

LeetCode 303. Range Sum Query -

作者: cb_guo | 来源:发表于2019-04-08 21:46 被阅读0次

题目描述

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.

题目思路

  • 思路一、Note 中指出,sumRange 会多次调用,所以构造函数O(n),sumRange函数O(1)
class NumArray {
public:
    vector<int> result;
    NumArray(vector<int>& nums) {
        result.push_back(0);
        int n = nums.size();
        int temp = 0;
        for(int i=0; i < n; i++){
            temp = temp + nums[i];
            result.push_back(temp);
        }
    }
    
    int sumRange(int i, int j) {
        return result[j+1] - result[i];
    }
};

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

总结展望

相关文章

网友评论

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

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