【一天一道LeetCode】#303.Range Sum Query - Immutable

一天一道LeetCode

本系列文章已全部上傳至我的github,地址:ZeeCoder‘s Github

歡迎大家關注我的新浪微博,我的新浪微博

我的個人博客已創建,歡迎大家持續關注!

一天一道leetcode系列依舊在csdn上繼續更新,除此係列以外的文章均遷移至我的個人博客

另外,本系列文章已整理並上傳至gitbook,網址:點我進

歡迎轉載,轉載請註明出處!

(一)題目

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.

(二)解題

題目大意:給定一個數組,計算它的區間和
解題思路:本題給出了NumArray的構造函數,區間和應該再構造函數內就已經計算好。

class NumArray {
public:
    NumArray(vector<int> &nums) {
        int size = nums.size();
        int sum = 0;
        for(int i = 0 ; i < size ; i++){
            vec.push_back(sum);//vec裏面存放第0~i-1位數的和。
            sum+=nums[i];
        }
        vec.push_back(sum);//第0~i位的和需要壓入vector
    }

    int sumRange(int i, int j) {
        return vec[j+1] - vec[i];//直接計算區間和
    }
public:
    vector<int> vec;
};
// Your NumArray object will be instantiated and called as such:
// NumArray numArray(nums);
// numArray.sumRange(0, 1);
// numArray.sumRange(1, 2);
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章