zoukankan      html  css  js  c++  java
  • 303 Range Sum Query

    给定一个数组,求出数组从索引 i 到 j  (i ≤ j) 范围内元素的总和,包含 i,  j 两点。
    例如:
    给定nums = [-2, 0, 3, -5, 2, -1],求和函数为sumRange()
    sumRange(0, 2) -> 1
    sumRange(2, 5) -> -1
    sumRange(0, 5) -> -3
    注意:
        你可以假设数组不可变。
        会多次调用 sumRange 方法。
    详见:https://leetcode.com/problems/range-sum-query-immutable/description/

    C++:

    方法一:

    class NumArray {
    public:
        NumArray(vector<int> nums) {
            dp=nums;
            for(int i=1;i<nums.size();++i)
            {
                dp[i]+=dp[i-1];
            }
        }
        
        int sumRange(int i, int j) {
            return i==0?dp[j]:dp[j]-dp[i-1];
        }
    private:
        vector<int> dp;
    };
    
    /**
     * Your NumArray object will be instantiated and called as such:
     * NumArray obj = new NumArray(nums);
     * int param_1 = obj.sumRange(i,j);
     */
    

     方法二:

    class NumArray {
    public:
        NumArray(vector<int> nums) {
            dp.resize(nums.size()+1,0);
            for(int i=1;i<=nums.size();++i)
            {
                dp[i]=dp[i-1]+nums[i-1];
            }
        }
        
        int sumRange(int i, int j) {
            return dp[j+1]-dp[i];
        }
    private:
        vector<int> dp;
    };
    
    /**
     * Your NumArray object will be instantiated and called as such:
     * NumArray obj = new NumArray(nums);
     * int param_1 = obj.sumRange(i,j);
     */
    

     参考:https://www.cnblogs.com/grandyang/p/4952464.html

  • 相关阅读:
    内存与缓存认识
    翻转字符串里的单词
    c++ STD Gems07
    C++ STD Gems06
    C++ STD Gems05
    Silverlight RIA Services基础专题
    超漂亮的WPF界面框架(Modern UI for WPF)
    实验三——阶乘
    实验二
    实验一 Java环境的搭建&Eclipse的安装
  • 原文地址:https://www.cnblogs.com/xidian2014/p/8830781.html
Copyright © 2011-2022 走看看