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);

    注意边界

  • 相关阅读:
    币值转换
    第八周作业
    第七周作业
    第五周编程总结
    第四周编程总结
    第三周编程总结
    7-1 查找整数
    7-2 求最大值及其下标
    秋季学习总结
    对我影响最大的三个老师
  • 原文地址:https://www.cnblogs.com/guoguolan/p/5632093.html
Copyright © 2011-2022 走看看