博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
leetCode 303. Range Sum Query - Immutable | Dynamic Programming
阅读量:7192 次
发布时间:2019-06-29

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

303. Range Sum Query - Immutable 

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


Note:

  1. You may assume that the array does not change.

  2. There are many calls to sumRange function.

题目大意:求数组一个连续子集的和。

思路:

1.可以直接找到数组子集的起始位置,连续相加到终止位置,

就可以得到答案。这样的话,没计算一次都要连续相加,比较麻烦。所以想到下面的思路。

2.用一个数组来存放当前元素的之前元素的和。

例如:

vector<int> source,源数组

vector<int> preITotal,用来存放source前i个元素的和,包括第i个元素。

以后每次计算范围源数组[i,j]范围子集的和,preITotal[j] - preITotal[i-1].计算即可。


代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class 
NumArray {
private
:
    
vector<
int
> preITotal;
//存放前i个元素的和
public
:
    
NumArray(vector<
int
> &nums) {
        
if
(nums.empty())
            
return
;
        
preITotal.push_back(nums[0]);
        
for
(
int 
i = 1; i < nums.size(); ++i)
            
preITotal.push_back(preITotal[i-1] + nums[i]);
    
}
 
    
int 
sumRange(
int 
i, 
int 
j) {
        
if
(0 == i)
            
return 
preITotal[j];
        
return 
preITotal[j] - preITotal[i - 1];
    
}
};
 
 
// Your NumArray object will be instantiated and called as such:
// NumArray numArray(nums);
// numArray.sumRange(0, 1);
// numArray.sumRange(1, 2);

总结:

题目标注为动态规划,开始怎么也想不出哪里用到动态规划的思想了。当把当前的结果记录下来,以后使用这一点,和动态规划挂钩了。

本文转自313119992 51CTO博客,原文链接:http://blog.51cto.com/qiaopeng688/1844975

转载地址:http://asxkm.baihongyu.com/

你可能感兴趣的文章
javascript函数以及作用域简介
查看>>
Windows Phone 编程中页面间传值方法 - [WP开发]
查看>>
apollo实现c#与android消息推送(四)
查看>>
Spring 上下文操作工具类 ContextUtils
查看>>
程序员的智囊库系列之3--分布式文件系统(Distributed file systems)
查看>>
工具推荐|程序员必须知道的11款新型编程工具
查看>>
Python入门之基础语法
查看>>
poj 2714 Random Walk
查看>>
SQL Server中数据的存储
查看>>
jQuery 属性操作方法
查看>>
LeetCode——Longest Consecutive Sequence
查看>>
Activity转换为View和把图片转换为View
查看>>
參考mudo logging写的win下logging
查看>>
云数据库PolarDB(一)
查看>>
[数据结构] 迷宫问题(栈和队列,深搜和广搜)
查看>>
找不到对象?也许你应该这样做
查看>>
Hadoop集群动态服役新的数据节点&&退役数据节点
查看>>
p4137 Rmq Problem / mex
查看>>
python学习之路---day16--面向对象
查看>>
打造一个高逼格的android开源项目——小白全攻略 (转)
查看>>