LeetCode 303. Range Sum Query -

2019-04-08  本文已影响0人  cb_guo

题目描述

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:

题目思路

class NumArray {
public:
    vector<int> result;
    NumArray(vector<int>& nums) {
        result.push_back(0);
        int n = nums.size();
        int temp = 0;
        for(int i=0; i < n; i++){
            temp = temp + nums[i];
            result.push_back(temp);
        }
    }
    
    int sumRange(int i, int j) {
        return result[j+1] - result[i];
    }
};

/**
 * Your NumArray object will be instantiated and called as such:
 * NumArray* obj = new NumArray(nums);
 * int param_1 = obj->sumRange(i,j);
 */

总结展望

上一篇下一篇

猜你喜欢

热点阅读