Range Sum Query - Immutable – LeetCode 303
Problem
Description
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
Answer
Original
Code
1 | class NumArray { |
思路
因为不可变所以建立一个缓存,用空间换时间,对于map[n] = num[1] + … + num[n],然后自然可得sumRange(i,j) = map[j] - map[i]。时间复杂度$O(n)$,空间复杂度$O(n)$。
耗时$163$ ms,排名$16.83\%$
Better
思路
还没看到更好的思路。