zoukankan      html  css  js  c++  java
  • LeetCode-307 Range Sum Query

    题目描述

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

    The update(i, val) function modifies nums by updating the element at index i to val.

    题目大意

    实现两个操作:更新数组,求数组范围内数字之和。

    示例

    E1

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

    解题思路

    保存一个vector数组,更新时以O(1)时间复杂度更新,求和时以O(N)时间复杂度遍历数组求和。

    复杂度分析

    时间复杂度:O(N)

    空间复杂度:O(N)

    代码

    class NumArray {
    public:
        NumArray(vector<int>& nums) {
            for(int n : nums)
                num.push_back(n);
        }
        
        void update(int i, int val) {
            num[i] = val;
        }
        
        int sumRange(int i, int j) {
            int sum = 0;
            for(int k = i; k <= j; ++k)
                sum += num[k];
            return sum;
        }
        
    private:
        vector<int> num;
    };
    
    /**
     * Your NumArray object will be instantiated and called as such:
     * NumArray* obj = new NumArray(nums);
     * obj->update(i,val);
     * int param_2 = obj->sumRange(i,j);
     */
  • 相关阅读:
    软件开发规范
    Fail2ban + firewalld 防护doss攻击
    SourceTree&Git部分名词解释
    训子
    一个网络下,手机如何访问本地网址
    tempalte.js的一般用法
    template.js的介绍
    获取URL中的参数
    js判断苹果和安卓端或者wp端
    HTML5与WebGL编程
  • 原文地址:https://www.cnblogs.com/heyn1/p/11163869.html
Copyright © 2011-2022 走看看