LeetCode學習篇十一——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

難度:easy 通過率:26.0%
這道題借用一個數組記錄從第0項加到第i項的和t[i],然後在return的時候直接減掉多餘的項即可。算法複雜度:O(n)

class NumArray {
public:
    vector<int> t;
    NumArray(vector<int> &nums) {
        t = vector<int>(nums.size(), 0);
        for(int i = 0; i < nums.size(); i++) {
            if(i > 0) t[i] = t[i-1]+nums[i];
            else  t[0] = nums[0];
        }
    }

    int sumRange(int i, int j) {
        if(i == 0) return t[j];
        return t[j]- t[i-1];
    }
};
發佈了37 篇原創文章 · 獲贊 3 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章