303. Range Sum Query - Immutable
2016-05-22 03:32
489 查看
1.Question
Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive.
Example:
Note:
You may assume that the array does not change.
There are many calls to sumRange function.
2.Code
3.Note
a.
这个题里我们要注意,sumRange() 会多次调用,如果直接遍历求和会超时。那么,我们用动态规划,用数组dp 记录0~i的和,表示为dp[i]。这样如果i == 0则sumRange(i, j)返回dp[j]即可, i != 0时, i~j 的和可以用dp[j] - dp[i-1]表示。
b.
dp是个vector,初始化分配空间很重要。否则会出现RE.
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.
2.Code
class NumArray { private: vector<int> dp; public: NumArray(vector<int> &nums) { dp = nums; for(int i = 1, size = nums.size(); i < size; i++) dp[i] += dp[i-1]; //实际上也是dp[i] = dp[i-1] + nums[i] } int sumRange(int i, int j) { return i == 0 ? dp[j] : dp[j] - dp[i-1]; } }; // Your NumArray object will be instantiated and called as such: // NumArray numArray(nums); // numArray.sumRange(0, 1); // numArray.sumRange(1, 2);
3.Note
a.
这个题里我们要注意,sumRange() 会多次调用,如果直接遍历求和会超时。那么,我们用动态规划,用数组dp 记录0~i的和,表示为dp[i]。这样如果i == 0则sumRange(i, j)返回dp[j]即可, i != 0时, i~j 的和可以用dp[j] - dp[i-1]表示。
b.
dp是个vector,初始化分配空间很重要。否则会出现RE.
相关文章推荐
- [leetcode] 【数组】128. Longest Consecutive Sequence
- 基于Vue.js的表格分页组件
- 关于easyui整合polymer中tab切换页面不匹配的解决(更新中)
- Android中在子线程中更新UI的三种方式
- Android Studio 中build.gradle文件的详细解析
- iOS 3D Touch 实现UITableViewCell 预览
- Ubuntu使用sudo命令出现must be setuid root错误的解决方法
- 60. Permutation Sequence
- LeetCode 63. Unique Paths II(唯一路径)
- LeetCode 62. Unique Paths
- UISplitViewController 分屏控制器
- UITableView初识(1)
- UITableView--多组数据显示
- 从技术实现角度看Android UI设计
- Arduino 和 MQ-135 空气污染气体传感器 实验
- iOS学习之UIView
- 29.UITabBarController
- Hive ORC和Parquet
- 【Leetcode】Longest Increasing Subsequence
- iOS中常用UI层方法总结