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

    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:

    1. You may assume that the array does not change.
    2. There are many calls to sumRange function.

    给定一个int数组,返回i和j之间的元素总和,注意时间复杂度

    思路:dp问题,  sums[i]表示0到i之间数据的总和,这样sums[j]-sums[i]就是i到j之间的总和

     1 class NumArray {
     2     
     3     int[] sums;
     4     public NumArray(int[] nums) {
     5         sums = new int[nums.length];
     6         if (nums.length == 0) return;
     7         sums[0] = nums[0];
     8         for (int i=1;i<nums.length;i++)
     9         {
    10             sums[i] = sums[i-1] + nums[i];
    11         }        
    12     }
    13     
    14     public int sumRange(int i, int j) {
    15       return i==0?sums[j]:sums[j]-sums[i-1];  
    16     }
    17 }
  • 相关阅读:
    『笔记』数学数论(八)
    『笔记』BSGS
    『笔记』组合数学(六)
    01 分数规划
    高斯消元
    拉格朗日插值法
    洛谷网课数论
    [IOI2013]robots 机器人
    P3530 [POI2012]FES-Festival
    NOIP 2015 day1
  • 原文地址:https://www.cnblogs.com/wzj4858/p/7687805.html
Copyright © 2011-2022 走看看