@author: sdubrz
@date: 2020.03.30
題目難度: 簡單
考察內容:動態規劃
原題鏈接 https://leetcode-cn.com/problems/range-sum-query-immutable/
題目的著作權歸領釦網絡所有,商業轉載請聯繫官方授權,非商業轉載請註明出處。
解題代碼轉載請聯繫 lwyz521604#163.com
給定一個整數數組 nums,求出數組從索引 i 到 j (i ≤ j) 範圍內元素的總和,包含 i, j 兩點。
示例:
給定 nums = [-2, 0, 3, -5, 2, -1],求和函數爲 sumRange()
sumRange(0, 2) -> 1
sumRange(2, 5) -> -1
sumRange(0, 5) -> -3
說明:
- 你可以假設數組不可變。
- 會多次調用 sumRange 方法。
解法
class NumArray {
public int[] sums;
public int n;
public NumArray(int[] nums) {
n = nums.length;
if(n==0){
return;
}
sums = new int[n];
sums[0] = nums[0];
for(int i=1; i<n; i++){
sums[i] = sums[i-1] + nums[i];
}
}
public int sumRange(int i, int j) {
if(i==0){
return sums[j];
}
else{
return sums[j] - sums[i-1];
}
}
}
/**
* Your NumArray object will be instantiated and called as such:
* NumArray obj = new NumArray(nums);
* int param_1 = obj.sumRange(i,j);
*/
下面是提交的結果:
執行結果:通過
執行用時 : 17 ms, 在所有 Java 提交中擊敗了 45.09% 的用戶
內存消耗 : 42.3 MB, 在所有 Java 提交中擊敗了 49.57% 的用戶
需要注意的是最初沒有考慮到空數組"[[[]]]"
的情況,導致沒有通過,因而當題目中沒有明確說明不可能輸入空數組時,要記得檢查一下。