leetcode 303 : Range Sum Query - Immutable

1、原题如下:
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、解题如下:

class NumArray {
public:
    vector<int> nums_accumulation_copy;
    NumArray(vector<int> &nums) {
        nums_accumulation_copy=nums;
        for(int a=1;a<nums.size();a++)
        {           nums_accumulation_copy[a]+=nums_accumulation_copy[a-1];
        }
    }

    int sumRange(int i, int j) {
        return (i==0)?nums_accumulation_copy[j]:(nums_accumulation_copy[j]-nums_accumulation_copy[i-1]);
    }
};
阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/l3368bcttqnqn/article/details/49944773
文章标签: leetcode c++ 面试
个人分类: 编程语言学习
上一篇leetcode 301 : Remove Invalid Parentheses
下一篇leetcode 304 : Range Sum Query 2D - Immutable
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭