AcWing
  • 首页
  • 活动
  • 题库
  • 竞赛
  • 应用
  • 更多
    • 题解
    • 分享
    • 商店
    • 吐槽
  • App
  • 登录/注册

LeetCode 303. 区域和检索 - 数组不可变    原题链接    简单

作者: 作者的头像   gcc7 ,  2022-11-25 15:55:33 ,  所有人可见 ,  阅读 67


1


参考文献

区域检索,前缀和的应用,注意下标的映射,前缀和一般从1开始

C++ 代码

class NumArray {
public:
    vector<int> prefix_sum_;
    NumArray(vector<int>& nums) {
        int n = nums.size();
        // 下标从1开始
        prefix_sum_ = vector(n+1, 0);
        for(int i=1; i<=n; ++i)prefix_sum_[i] = prefix_sum_[i-1] + nums[i-1];
    }

    int sumRange(int left, int right) {
        ++left, ++right;
        return prefix_sum_[right] - prefix_sum_[left-1];
    }
};

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

0 评论

你确定删除吗?
1024
x

© 2018-2023 AcWing 版权所有  |  京ICP备2021015969号-2
用户协议  |  隐私政策  |  常见问题  |  联系我们
AcWing
请输入登录信息
更多登录方式: 微信图标 qq图标 qq图标
请输入绑定的邮箱地址
请输入注册信息