前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Range Sum Query - Immutable

Range Sum Query - Immutable

作者头像
卡尔曼和玻尔兹曼谁曼
发布2019-01-22 09:29:19
3590
发布2019-01-22 09:29:19
举报

303. Range Sum Query - Immutable

题目描述

Given an integer array nums, find the sum of the elements between indices i and j (ij), inclusive.

Example:

代码语言:javascript
复制
Given nums = [-2, 0, 3, -5, 2, -1]

sumRange(0, 2) -> 1
sumRange(2, 5) -> -1
sumRange(0, 5) -> -3

Note:

  1. You may assume that the array does not change.
  2. There are many calls to sumRange function.

思路分析

题目中提示给定的nums数组不变,而且sumRange()函数可能需要多次被调用。

这个就很简单了,我们计算出来当前位置元素到初始元素之间所有元素之和,并进行存储,每次需要求解给定区间元素之和的时候收尾相减即可。这样就可以大大减少调用多次sumRange()函数的计算时间。

注意:我们的和元素组成的数组中第一个元素是0。

其实,我觉得这道题并不完全能算得上一道动态规划的题目。但是LeetCode把这道题归类到动态规划中也说得过去吧。

C++示例

代码语言:javascript
复制
class NumArray {
private:
    vector<int> sums;
public:
    NumArray(vector<int> nums) {
        sums.push_back(0);
        for (int i = 0; i < nums.size(); ++i) {
            sums.push_back(nums[i] + sums[i]);
        }
    }

    int sumRange(int i, int j) {
        return sums[j + 1] - sums[i];
    }
};

int main() {
    vector<int> nums{-2, 0, 3, -5, 2, -1};
    NumArray obj(nums);
    int result = obj.sumRange(2, 5);
    cout << result << endl;
    return 0;
}

Scala示例

代码语言:javascript
复制
object RangeSumQuery {

  class NumArray(nums: Array[Int]) {

    private val sums = new Array[Int](nums.length + 1)
    for (i <- nums.indices)
      sums(i + 1) = sums(i) + nums(i)

    def sumRange(i: Int, j: Int): Int = {
      sums(j + 1) - sums(i)
    }
  }

  def main(args: Array[String]): Unit = {
    val nums = Array(-2, 0, 3, -5, 2, -1)
    val obj = new NumArray(nums)
    val result = obj.sumRange(2, 5)
    println(result)
  }
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018年09月08日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 303. Range Sum Query - Immutable
    • 题目描述
      • 思路分析
        • C++示例
          • Scala示例
          领券
          问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档