leetcode笔记:Range Sum Query - Immutable

来源:互联网 发布:知乎阿里云免费开通码 编辑:程序博客网 时间:2024/06/05 19:52

一. 题目描述

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) -> 1sumRange(2, 5) -> -1sumRange(0, 5) -> -3

二. 题目分析

给定一个数组nums,求出下标ij之间元素的和,这里假设i一定是小于或等于j的,且数组nums一般是不变的。

这道题应该不看提示就能想到比暴力方法更好的方案,在本题中,sumRange可能会被调用多次,因此如果每次调用时才对下标区间的元素进行累加,会导致效率低下。

可以采取的改进方法是,在构造函数NumArray(vector<int> &nums)中,输入了数组nums,同时计算了从第一个元素到每个下标元素所有元素的累积和,保存到新数组sums的对应位置中,这样,每次寻找下标ij之间元素的和,只需直接返回: sums[j] - sum[i - 1]即可。

三. 示例代码

class NumArray {public:    NumArray(vector<int> &nums) {        if (nums.empty()) return;        else        {            sums.push_back(nums[0]);            //求得给定数列长度            int len = nums.size();            for (int i = 1; i < len; ++i)                sums.push_back(sums[i - 1] + nums[i]);        }    }    int sumRange(int i, int j) {        return sums[j] - sums[i - 1];    }private:    //存储数列和    vector<int> sums;};// Your NumArray object will be instantiated and called as such:// NumArray numArray(nums);// numArray.sumRange(0, 1);// numArray.sumRange(1, 2);
3 0
原创粉丝点击