1. 程式人生 > >303. Range Sum Query - Immutable(數組區間和)

303. Range Sum Query - Immutable(數組區間和)

HERE img arr mmu ice you 其中 func not

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.

求區間 i ~ j 的和,可以轉換為 sum[j + 1] - sum[i],其中 sum[i] 為 0 ~ i - 1 的和。

時間復雜度:o(n) 空間復雜度:o(n)

技術分享圖片

303. Range Sum Query - Immutable(數組區間和)