• 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);

  • 相关阅读:
    tcp_tw_recycle 的问题, 使用某一个wifi,APP老是连接不上网络
    stackoverflow 的架构
    服务器的返回码总结
    iOS10 app连接不上网络的问题
    nsurl 测试ATS
    处理数据队列
    换手率的公司使用MQTT的框架
    导入charts开源库到工程里面
    极光推送的推送方式
    自己生成一个NDK的浅析
  • 原文地址:https://www.cnblogs.com/CodingGirl121/p/5477231.html
Copyright © 2020-2023  润新知