LeetCode No.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

Note:

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

===========================================================================

題目鏈接:https://leetcode.com/problems/range-sum-query-immutable/

題目大意:給定一個數組,多次使用sumRange(i,j)返回數組中從i到j的元素之和。

思路:先用一個和nums一樣大的數組sums存儲nums的和,其中sums[i] = sums[i-1] + nums[i],時間複雜度爲O(N),空間複雜度爲O(N)。最後計算sumRange(i,j)時,結果就是sums[j] - sums[i] + nums[i]sums[j] - sums[i] + nums[i],這樣的時間複雜度爲O(1),因爲多次使用sumRange()函數,所以這樣做能大大減少算法運算時間。

參考代碼:

class NumArray {
public:
    NumArray(vector<int> &nums) {
        this -> nums = nums ;
        int n = nums.size() ;
        if ( n )
        {
            sums = vector <long long> ( n ) ; 
            sums[0] = nums[0] ;
            for ( int i = 1 ; i < n ; i ++ )
                sums[i] = sums[i-1] + nums[i] ;
        }
    }

    int sumRange(int i, int j) {
        return sums[j] - sums[i] + nums[i] ;
    }
private:
    vector <long long> sums ;
    vector <int> nums ;
};


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


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章