日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

Leetcode题目:Range Sum Query - Immutable

發布時間:2025/3/19 31 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Leetcode题目: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.
  • 題目解答:這個題目說了,會反復的求一段數字的和,但是默認數組不變。這么說來,就是求和的復雜度就是主要的復雜度。那么可以先把它們存起來,然后再求得時候,直接把結果返回來。需要注意的是,求[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);

    轉載于:https://www.cnblogs.com/CodingGirl121/p/5477231.html

    總結

    以上是生活随笔為你收集整理的Leetcode题目:Range Sum Query - Immutable的全部內容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。