Skip to content

Commit 0fb7295

Browse files
committed
🎉 #303. Range Sum Query - Immutable
1 parent 6f1fe57 commit 0fb7295

File tree

2 files changed

+69
-0
lines changed

2 files changed

+69
-0
lines changed

Diff for: #303. Range Sum Query - Immutable/Solution.java

+33
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
/*
2+
* @Author: Goog Tech
3+
* @Date: 2020-09-15 15:07:30
4+
* @LastEditTime: 2020-09-15 15:11:43
5+
* @Description: https://leetcode-cn.com/problems/range-sum-query-immutable/
6+
* @FilePath: \leetcode-googtech\#303. Range Sum Query - Immutable\Solution.java
7+
* @Reference: https://leetcode-cn.com/problems/range-sum-query-immutable/solution/marveljian-dan-de-xue-xi-bi-ji-303-by-tyanyonecanc/
8+
* @WebSite: https://algorithm.show/
9+
*/
10+
11+
class NumArray {
12+
13+
private int[] sum;
14+
15+
// DP : 动态规划
16+
public NumArray(int[] nums) {
17+
sum = Arrays.copyOf(nums, nums.length);
18+
for(int i = 1; i < sum.length; i++) {
19+
// sum[i] 的值为 sum[0] 到 sum[i] 的所有值之和
20+
sum[i] += sum[i - 1];
21+
}
22+
}
23+
24+
public int sumRange(int i, int j) {
25+
return (i == 0) ? sum[j] : (sum[j] - sum[i - 1]);
26+
}
27+
}
28+
29+
/**
30+
* Your NumArray object will be instantiated and called as such:
31+
* NumArray obj = new NumArray(nums);
32+
* int param_1 = obj.sumRange(i,j);
33+
*/

Diff for: #303. Range Sum Query - Immutable/Solution.py

+36
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
'''
2+
Author: Goog Tech
3+
Date: 2020-09-15 15:07:34
4+
LastEditTime: 2020-09-15 15:08:56
5+
Description: https://leetcode-cn.com/problems/range-sum-query-immutable/
6+
FilePath: \leetcode-googtech\#303. Range Sum Query - Immutable\Solution.py
7+
Reference: https://leetcode-cn.com/problems/range-sum-query-immutable/solution/marveljian-dan-de-xue-xi-bi-ji-303-by-tyanyonecanc/
8+
WebSite: https://algorithm.show/
9+
'''
10+
11+
class NumArray(object):
12+
13+
# DP : 动态规划
14+
def __init__(self, nums):
15+
"""
16+
:type nums: List[int]
17+
"""
18+
if not nums: return
19+
self.result = [0] * len(nums)
20+
self.result[0] = nums[0]
21+
for i in range(1, len(nums)):
22+
# result[i] 的值为 nums[0] 到 nums[i] 的所有值之和
23+
self.result[i] = self.result[i - 1] + nums[i]
24+
25+
def sumRange(self, i, j):
26+
"""
27+
:type i: int
28+
:type j: int
29+
:rtype: int
30+
"""
31+
if i == 0: return self.result[j]
32+
else: return self.result[j] - self.result[i - 1]
33+
34+
# Your NumArray object will be instantiated and called as such:
35+
# obj = NumArray(nums)
36+
# param_1 = obj.sumRange(i,j)

0 commit comments

Comments
 (0)