Range Sum Query - Immutable(easy)

原创 2015年11月19日 23:21:50

1.这道题目与pat中的1046. Shortest Distance (20)相类似;

2.使用一个数组dp[i],记录0到第i个数的和

3.求i到j之间的和时,输出dp[j]-dp[i]+num[i]即可。


AC代码如下:

class NumArray {
public:

    vector<int> dp;
    vector<int> num;
    NumArray(vector<int> &nums) {
        int n=nums.size();
        dp=vector<int>(n,0);
        num=nums;
        for(int i=0;i<n;i++)
        {
            if(i>0)
                dp[i]=dp[i-1]+nums[i];
            else
                dp[0]=nums[0];
        }
    }

    int sumRange(int i, int j) {
        return dp[j]-dp[i]+num[i];
    }
};


// Your NumArray object will be instantiated and called as such:
// NumArray numArray(nums);
// numArray.sumRange(0, 1);
// numArray.sumRange(1, 2);


版权声明:本文为博主原创文章,未经博主允许不得转载。

相关文章推荐

leetcode 303: Range Sum Query - Immutable

Range Sum Query - Immutable Total Accepted: 696 Total Submissions: 2406 Difficulty: Eas...
  • xudli
  • xudli
  • 2015-11-10 17:47
  • 4514

LeetCode(303)Range Sum Query - Immutable

题目Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusi...
  • fly_yr
  • fly_yr
  • 2015-12-04 13:31
  • 3150

303. Range Sum Query - Immutable [easy] (Python)

题目链接https://leetcode.com/problems/range-sum-query-immutable/题目原文 Given an integer array nums, find...

动态规划——303. Range Sum Query - Immutable[easy]

题目描述 Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j),...
  • xiegr
  • xiegr
  • 2017-05-06 19:31
  • 57

算法设计Week11 LeetCode Algorithms Problem #304 Range Sum Query 2D - Immutable

题目描述: Given a 2D matrix matrix, find the sum of the elements inside the rectangle defined by its u...

DP (1) -- Range Sum Query - Immutable, House Robber, Climbing Stairs

Range Sum Query - Immutable,House Robber

304. Range Sum Query 2D - Immutable 等题

303. Range Sum Query原题: Given an integer array nums, find the sum of the elements between indices i...

LeetCode 304 Range Sum Query 2D - Immutable(维护二维数组的前缀和)

Given a 2D matrix matrix, find the sum of the elements inside the rectangle defined by its upper lef...

LeetCode 304 Range Sum Query 2D - Immutable(范围求和2D - 不可变)

翻译给定一个2D矩阵matrix,找出其中以左上角(row1,col1)和右下角(row2,col2)定义的矩形边界的元素的和。(译者注:包括边界)以上矩形 范围内的元素和为8。例如, 给定 mat...
  • NoMasp
  • NoMasp
  • 2016-06-29 15:33
  • 1305

Range Sum Query 2D - Immutable

题目描述: Given a 2D matrix matrix, find the sum of the elements inside the rectangle defined by its u...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

(最多只允许输入30个字)