LeetCode 303. Range Sum Query - Immutable
2017-05-01 11:26
525 查看
题目:
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.
思路:
就是求区间i和j之前的值的和,因为是同一个数组,测试用例为取不同的i和j,如果不考虑效率,每次都是i到j的值相加,但是这样如果对同一个数组测试用例多了之后效率很低;所以要考虑效率问题,求出nums的前i个数的值放到sums中,每次只要调用
代码实现:
输出结果: 179ms
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.
思路:
就是求区间i和j之前的值的和,因为是同一个数组,测试用例为取不同的i和j,如果不考虑效率,每次都是i到j的值相加,但是这样如果对同一个数组测试用例多了之后效率很低;所以要考虑效率问题,求出nums的前i个数的值放到sums中,每次只要调用
sums[j]-sums[i-1]即可
代码实现:
class NumArray { public: NumArray(vector<int> nums) { if (nums.empty()){//如果nums为空,直接返回 return ; } else{ sums.push_back(nums[0]); //求得给定数列长度 int len = nums.size(); for (int i = 1; i < len; ++i){//分别求nums的前i个和放入sums中 sums.push_back(sums[i - 1] + nums[i]); } } } int sumRange(int i, int j) { if (0 == i){ return sums[j]; } int len = sums.size(); if (i < 0 || i >= len || j < 0 || j >= len || i > j){//如果是这些条件,都是不满足的 return 0; } return sums[j] - sums[i-1];//即是sums的前j个和-前i-1个和 } private: //sums的第i个值即为nums的前i个数的和(i从0开始) vector<int> sums; }; /** * Your NumArray object will be instantiated and called as such: * NumArray obj = new NumArray(nums); * int param_1 = obj.sumRange(i,j); */
输出结果: 179ms
相关文章推荐
- 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 求区间和
- 【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(数组求和)