码迷,mamicode.com
首页 > 其他好文 > 详细

(leetcode题解)Range Sum Query - Immutable

时间:2017-06-16 22:07:12      阅读:162      评论:0      收藏:0      [点我收藏+]

标签:etc   logs   table   题目   color   back   log   题解   example   

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:

  1. You may assume that the array does not change.
  2. There are many calls to sumRange function.

题意是给定一个数组返回给定位置之间的元素的和。

这道题如果只求单独一个是很简单的,直接算就好,但是题目要求可能存在多个同时调用,这个我们就要考虑将每一次的结果保留下来了,这是自然想到dp。

累计到[0,i]所有位的和用sum[i+1]表示,要求就是sum[j+1]-sum[i]。C++实现如下:

class NumArray {
public:
    NumArray(vector<int> nums) {
        sum.push_back(0);
        for(int i=0;i<nums.size();i++)
            sum.push_back(sum[i]+nums[i]);
    }
    
    int sumRange(int i, int j) {
        if(i==0)
            return sum[j+1];
        return sum[j+1]-sum[i];
    }
private:
    vector<int> sum;
};

 

(leetcode题解)Range Sum Query - Immutable

标签:etc   logs   table   题目   color   back   log   题解   example   

原文地址:http://www.cnblogs.com/kiplove/p/7029282.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!