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

    Given an integer array nums, find the sum of the elements between indices i and j (ij), 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.

    Solution:

     1 public class NumArray {
     2     int[] sums;
     3     public NumArray(int[] nums) {
     4         sums = new int[nums.length];
     5         int sum = 0;
     6         for (int i=0;i<nums.length;i++){
     7             sum += nums[i];
     8             sums[i] = sum;
     9         }
    10     }
    11 
    12     public int sumRange(int i, int j) {
    13         int sum1 = (i==0) ? 0 : sums[i-1];
    14         int sum2 = sums[j];
    15         return sum2 - sum1;
    16     }
    17 }
    18 
    19 
    20 // Your NumArray object will be instantiated and called as such:
    21 // NumArray numArray = new NumArray(nums);
    22 // numArray.sumRange(0, 1);
    23 // numArray.sumRange(1, 2);
  • 相关阅读:
    区块链
    区块链
    区块链
    区块链
    区块链 – 介绍
    区块链 教程
    Matplotlib 直方图
    Matplotlib 饼图
    Matplotlib 柱状图
    Matplotlib 多个图形
  • 原文地址:https://www.cnblogs.com/lishiblog/p/5772706.html
Copyright © 2011-2022 走看看