【Leetcode 303】关关的刷题日记67–Leetcode 303 Range Sum Query – Immutable

时间:2022-05-08
本文章向大家介绍【Leetcode 303】关关的刷题日记67–Leetcode 303 Range Sum Query – Immutable,主要内容包括题目、思路、基本概念、基础应用、原理机制和需要注意的事项等,并结合实例形式分析了其使用技巧,希望通过本文能帮助到大家理解应用这部分内容。

关关的刷题日记67 – Leetcode 303 Range Sum Query – Immutable

题目

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 Note: You may assume that the array does not change. There are many calls to sumRange function.

题目的意思是给定一个数组,求指定子序列的和。数组是不发生变化的,而且会多次求子序列的和。

思路

思路:如果要是每次都遍历数组求子序列和的话,因为会调用很多次肯定会超时。所以我们设置数组re,re[i]表示该数组前i个元素的和。每次调用sumRange的时候,直接返回re[j]-re[i-1]即可。

class NumArray {public:
    vector<int>re;

    NumArray(vector<int> nums) {
        int sum=0;
        for(int i=0; i<nums.size(); i++)
        {
            re.push_back(sum+nums[i]);
            sum=re[i];
        }
    }

    int sumRange(int i, int j) {
        if(i==0)
            return re[j];
        return re[j]-re[i-1];
    }};/**
 * Your NumArray object will be instantiated and called as such:
 * NumArray obj = new NumArray(nums);
 * int param_1 = obj.sumRange(i,j);
 */

以上就是关关关于这道题的总结经验,希望大家能够理解,有什么问题可以在我们的专知公众号平台上交流或者加我们的QQ专知-人工智能交流群 426491390,也可以加入专知——Leetcode刷题交流群(请先加微信小助手weixinhao: Rancho_Fang)。