Range Sum Query - Immutable (E)
題目
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.
題意
給定一個陣列,求從下標i到j的元素之和,
思路
因為方法可能被多次呼叫,因而可以用快取進行優化:另設陣列sum,sum[i]表示nums中前i個元素之和,因此i到j的元素之和就可以表示為sum[j + 1] - sum[i],
代碼實作
Java
class NumArray {
private 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];
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/38880.html
標籤:其他
上一篇:0041. First Missing Positive (H)
下一篇:有大佬知道怎么樣制裁網路暴力嘛?
