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

  • 相关阅读:
    NOI2018:屠龙勇士
    Hello world!
    bzoj5月月赛订正
    codeforces906 D
    bzoj2728 [HNOI2012]与非
    bzoj3884上帝与集合的正确用法
    bzoj2817[ZJOI2012]波浪
    2017多校联合赛1[题解]
    论如何优雅的用bitset来求四维偏序
    bzoj1488[HNOI2009]图的同构
  • 原文地址:https://www.cnblogs.com/CodingGirl121/p/5477231.html
Copyright © 2011-2022 走看看