Fork me on GitHub

[leetcode-303-Range Sum Query - Immutable]

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
You may assume that the array does not change.
There are many calls to sumRange function.

思路:

用数组保存当前元素左边所有元素的和,求区间i和j之间元素和的时候,只需计算sum[j]-sum[i-1]即可。

时间复杂度为O(1),空间复杂度为O(n)

vector<int> nums;
    Solution(vector<int> num)
    {
    
        for (int i = 1; i < num.size();i++)
        {
            num[i] = num[i] + num[i - 1];//存储和
        }
        this->nums = num;
    }
    int sumRange(int i, int j)
    {
        if (nums.size() == 0) return NULL;
        if (i ==0)return nums[j];
        return nums[j] - nums[i - 1];
    }

参考:

https://discuss.leetcode.com/topic/29194/java-simple-o-n-init-and-o-1-query-solution/3

posted @ 2017-03-03 10:01  hellowOOOrld  阅读(188)  评论(0编辑  收藏  举报