zoukankan      html  css  js  c++  java
  • [leetcode] 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:
    You may assume that the array does not change.
    There are many calls to sumRange function.

    分析:利用一个数组sum缓存累积的和,建立数组sum的时间复杂度O(N),之后每次sumRange查询时间复杂度都为O(1).

    Java代码:

    public class NumArray{
        int[] sum;
        public NumArray(int[] nums) {
            sum = new int[nums.length + 1];
            for (int i = 0; i < nums.length; i++) {
                sum[i+1] = sum[i] + nums[i];
            }
        }
    
        public int sumRange(int i, int j) {
            return sum[j+1] - sum[i];
        }
    }
  • 相关阅读:
    三、linux系统管理
    二、基本命令
    一、基本环境
    mysql-day4
    mysql-day3
    mysql-day2
    mysql-day1
    3、线性表的链式存储结构
    2、线性表之顺序表
    1、时间复杂度
  • 原文地址:https://www.cnblogs.com/lasclocker/p/4956096.html
Copyright © 2011-2022 走看看