zoukankan      html  css  js  c++  java
  • leetcode 303. Range Sum Query

    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
    

    前缀和思想。如果修改的次数比较多,那么就可以用线段树了,

    class NumArray {
    public:
        vector<int> sum;
        NumArray(vector<int> nums) {
            for (int i = 0; i < nums.size(); ++i) {
                if (sum.size()) sum.push_back(nums[i] + sum.back());
                else sum.push_back(nums[i]);
            }
        }
        
        int sumRange(int i, int j) {
            if (i < 1) return sum[j];
            else return sum[j] - sum[i-1];
        }
    };
    
    /**
     * Your NumArray object will be instantiated and called as such:
     * NumArray obj = new NumArray(nums);
     * int param_1 = obj.sumRange(i,j);
     */
    
  • 相关阅读:
    3
    2
    1
    11
    12
    8888888888
    99999999999
    88888888888
    77777777
    10.23
  • 原文地址:https://www.cnblogs.com/pk28/p/8485344.html
Copyright © 2011-2022 走看看