LeetCode 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.

题目思路

  • 思路一、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);
 */

总结展望

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容