LeetCode 303. Range Sum Query - Immutable
2017-05-28 00:10
363 查看
303. Range Sum Query - Immutable
一、问题描述
Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive.Note:
You may assume that the array does not change.
There are many calls to sumRange function.
二、输入输出
Example:Given nums = [-2, 0, 3, -5, 2, -1] sumRange(0, 2) -> 1 sumRange(2, 5) -> -1 sumRange(0, 5) -> -3
三、解题思路
是按照DP TAG来选的题目,结果这道题我实在是看不出来DP的影子。DP是用来解决最优化问题的,这个题完全就没有最优化的影子。如果每次都从i加到j TLE错误。提示里说了会调用方法很多次。全新的一个思路,只需要o(n)时间复杂度,o(n)的空间复杂度,如果不用sums数组,而是在原来的nums上修改,空间复杂度就成了o(1)
核心思想就是
sum(i, j) = sum(0, j) - sum(0, i-1)就是把从0到i的和记录下来,之后让求从i到j的和,主要做一次减法就行了,只需要常数时间。
class NumArray { public: vector<int> sums; NumArray(vector<int> nums) { if (nums.empty()) return; sums.push_back(nums[0]); for (int i = 1; i < nums.size(); ++i) { int lastSum = sums[i-1]; sums.push_back(lastSum + nums[i]); } } int sumRange(int i, int j) { if(i == 0) return sums[j]; return (sums[j] - sums[i-1]); } }; /** * Your NumArray object will be instantiated and called as such: * NumArray obj = new NumArray(nums); * int param_1 = obj.sumRange(i,j); */
相关文章推荐
- leetcode - 303. Range Sum Query - Immutable 【动态规划 + 间接逼近目标 + 区间计算 +刻度 + 距离计算方式 】
- Leetcode 303. Range Sum Query - Immutable (Easy) (cpp)
- LeetCode 303. Range Sum Query - Immutable
- [LeetCode]303. Range Sum Query - Immutable
- leetcode-303. Range Sum Query - Immutable
- leetcode 303. Range Sum Query - Immutable
- [Leetcode] 303. Range Sum Query - Immutable 解题报告
- LeetCode-303. Range Sum Query - Immutable
- 【LeetCode】303. Range Sum Query - Immutable
- [LeetCode]303. Range Sum Query - Immutable
- LeetCode笔记:303. Range Sum Query - Immutable
- [leetcode]: 303. Range Sum Query - Immutable
- Leetcode 303. Range Sum Query - Immutable & 307. Range Sum Query - Mutable
- LeetCode 303. Range Sum Query - Immutable
- leetcode_303. Range Sum Query - Immutable
- leetcode303.[DP] Range Sum Query - Immutable
- leetcode_303. Range Sum Query - Immutable 求区间和
- 【leetcode】303. Range Sum Query - Immutable
- [LeetCode]303. Range Sum Query - Immutable
- Leetcode:303. Range Sum Query - Immutable(week 8)