zoukankan      html  css  js  c++  java
  • [LeetCode] Range Sum Query

    The idea is fairly straightforward: create an array accu that stores the accumulated sum fornums such that accu[i] = nums[0] + ... + nums[i] in the initializer of NumArray. Then just return accu[j + 1] - accu[i] in sumRange. You may try the example in the problem statement to convince yourself of this idea.

    The code is as follows.


    C++

     1 class NumArray {
     2 public:
     3     NumArray(vector<int> &nums) {
     4         accu.push_back(0);
     5         for (int num : nums)
     6             accu.push_back(accu.back() + num);
     7     }
     8 
     9     int sumRange(int i, int j) {
    10         return accu[j + 1] - accu[i];
    11     }
    12 private:
    13     vector<int> accu;
    14 };
    15 
    16 
    17 // Your NumArray object will be instantiated and called as such:
    18 // NumArray numArray(nums);
    19 // numArray.sumRange(0, 1);
    20 // numArray.sumRange(1, 2); 

    Python

    class NumArray(object):
        def __init__(self, nums):
            """
            initialize your data structure here.
            :type nums: List[int]
            """
            self.accu = [0]
            for num in nums:
                self.accu += self.accu[-1] + num,
    
        def sumRange(self, i, j):
            """
            sum of elements nums[i..j], inclusive.
            :type i: int
            :type j: int
            :rtype: int 
            """
            return self.accu[j + 1] - self.accu[i]
    
    
    # Your NumArray object will be instantiated and called as such:
    # numArray = NumArray(nums)
    # numArray.sumRange(0, 1)
    # numArray.sumRange(1, 2)
  • 相关阅读:
    你不是在拯救世界就是在拯救世界的路上
    你可以去当程序员了
    郭美美是个好姑娘
    据说有个老太太
    生命的尽头
    有关程序的50个至理名言
    程序员是这样的
    新买移动硬盘
    如果有天你看到我疯了,其实就是你疯了
    写字楼里写字间
  • 原文地址:https://www.cnblogs.com/jcliBlogger/p/4952704.html
Copyright © 2011-2022 走看看