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.
     1 public class NumArray {
     2     private int[] sum;
     3     public NumArray(int[] nums) {
     4         sum = new int[nums.length+1];
     5         for(int i = 1; i < sum.length; i++)
     6             sum[i] = sum[i-1] + nums[i-1];
     7     }
     8 
     9     public int sumRange(int i, int j) {
    10         return sum[j+1] - sum[i];
    11     }
    12 }
    13 
    14 
    15 // Your NumArray object will be instantiated and called as such:
    16 // NumArray numArray = new NumArray(nums);
    17 // numArray.sumRange(0, 1);
    18 // numArray.sumRange(1, 2);

    注意边界

  • 相关阅读:
    额外的 string 操作
    vector 对象是如何增长的
    顺序容器操作
    容器库概览
    顺序容器概述
    特定容器算法
    泛型算法结构
    再探迭代器
    定制操作
    使用关联容器
  • 原文地址:https://www.cnblogs.com/guoguolan/p/5632093.html
Copyright © 2011-2022 走看看