博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode——Range Sum Query - Immutable
阅读量:4538 次
发布时间:2019-06-08

本文共 942 字,大约阅读时间需要 3 分钟。

Question

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.

Solution

简单的动态规划,依次累加,table[j] - table[i - 1]就表示两者之间的求和,注意i - 1可能越界。

Code

class NumArray {public:    NumArray(vector
nums) { int total = 0; for (int i = 0; i < nums.size(); i++) { total += nums[i]; table.push_back(total); } } int sumRange(int i, int j) { return (table[j] - ((i - 1) < 0 ? 0 : table[i - 1])); }private: vector
table; };/** * Your NumArray object will be instantiated and called as such: * NumArray obj = new NumArray(nums); * int param_1 = obj.sumRange(i,j); */

转载于:https://www.cnblogs.com/zhonghuasong/p/7500347.html

你可能感兴趣的文章
ASP.NET Razor 视图引擎编程参考
查看>>
Vue 基础篇
查看>>
malloc_free_new_delete
查看>>
Python中的open和codecs.open
查看>>
开发Servlet的方法(2)
查看>>
asp.net mvc 伪静态添加
查看>>
EA类图与代码同步
查看>>
Android Studio 智能感知无效
查看>>
javascript 日常
查看>>
让插件帮你优化代码
查看>>
ng 动态的生成option。
查看>>
ORACLE-12C-RAC INSTALL
查看>>
自定义引用类型的Enumerable.Union调用(原创)
查看>>
抽象类实例
查看>>
react context prop-types
查看>>
Java之路——Java初接触
查看>>
2018.12.27学习JavaScript
查看>>
Cocoa编程开发者手册
查看>>
C++框架_之Qt的开始部分_概述_安装_创建项目_快捷键等一系列注意细节
查看>>
理工之 A+B Problem III
查看>>