zoukankan      html  css  js  c++  java
  • Leetcode题目:Range Sum Query

    题目:

    Given an integer array nums, find the sum of the elements between indices i and j (ij), inclusive.

    Example:

    Given nums = [-2, 0, 3, -5, 2, -1]
    
    sumRange(0, 2) -> 1
    sumRange(2, 5) -> -1
    sumRange(0, 5) -> -3
    

     

    Note:

    1. You may assume that the array does not change.
    2. There are many calls to sumRange function.

    题目解答:这个题目说了,会反复的求一段数字的和,但是默认数组不变。这么说来,就是求和的复杂度就是主要的复杂度。那么可以先把它们存起来,然后再求得时候,直接把结果返回来。需要注意的是,求[2,5]的和就是求[0,5]的和减去[0,2]的和,再加上[2]这个位置的值。

    代码如下:

    class NumArray {
    public:
        NumArray(vector<int> &nums):nums(nums) {
            int sum = 0;
            for(int i = 0;i < nums.size();i++)
            {
                sum += nums[i];
                sums.push_back(sum);
            }
        }

        int sumRange(int i, int j) {
            if((i > j) || (i >= nums.size()) || (j >= nums.size()))
                return 0;
            return sums[j] - sums[i] + nums[i];
        }

    private:
        vector<int> sums;
        vector<int> &nums;
    };


    // Your NumArray object will be instantiated and called as such:
    // NumArray numArray(nums);
    // numArray.sumRange(0, 1);
    // numArray.sumRange(1, 2);

  • 相关阅读:
    Nbear讲解 之核心类CodeGenerator
    计算字符串显示的像素
    C# 加密算法[汇总]
    索引器的本质
    Excel[.xls|.xlsx|.csv] 导入 导出
    Spring.Net Ioc 实例
    反射中 BindingFlags标识
    C# 图片操作 常用方法 总结
    iTextSharp 生成pdf Form 实例
    玩转 Route
  • 原文地址:https://www.cnblogs.com/CodingGirl121/p/5477231.html
Copyright © 2011-2022 走看看