[LeetCode]303. Range Sum Query - Immutable

本文介绍了解决LeetCode 303题“Range Sum Query - Immutable”的一种高效方法。通过预先计算并存储从第0位到当前位置的累积和,避免了每次查询时重复计算区间和的问题,从而显著提高了查询效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

[LeetCode]303. Range Sum Query - Immutable

题目描述

这里写图片描述

思路

开始的思路:存数组,将对应的区间内的数字相加
优化:
对于每一位,存入的是从第0位到当前位的和
返回的时候返回 [j] - [i - 1]即可

代码

开始的思路

class NumArray {
public:
    vector<int> nums;
    NumArray(vector<int> nums) {
        for (int p : nums)
            this->nums.push_back(p);
    }

    int sumRange(int i, int j) {
        int sum = 0;
        for (; i <= j; ++i)
            sum += nums[i];
        return sum;
    }

};

优化后

#include <iostream>
#include <vector>

using namespace std;

class NumArray {
public:
    vector<int> nums;
    NumArray(vector<int> nums) {
        if (nums.size()) {
            this->nums.push_back(nums[0]);
            for (int i = 1; i < nums.size(); ++i)
                this->nums.push_back(nums[i] + this->nums[i - 1]);
        }
    }

    int sumRange(int i, int j) {
        if (i)
            return nums[j] - nums[i - 1];
        else
            return nums[j];
    }

};

int main() {
    vector<int> nums = { -2, 0, 3, -5, 2, -1 };
    NumArray s = NumArray(nums);
    cout << s.sumRange(0, 2) << endl;
    system("pause");
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值