-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path303.区域和检索-数组不可变.py
More file actions
63 lines (55 loc) · 1.34 KB
/
303.区域和检索-数组不可变.py
File metadata and controls
63 lines (55 loc) · 1.34 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#
# @lc app=leetcode.cn id=303 lang=python
#
# [303] 区域和检索 - 数组不可变
#
# https://leetcode-cn.com/problems/range-sum-query-immutable/description/
#
# algorithms
# Easy (56.63%)
# Likes: 105
# Dislikes: 0
# Total Accepted: 19.6K
# Total Submissions: 34.2K
# Testcase Example: '["NumArray","sumRange","sumRange","sumRange"]\n[[[-2,0,3,-5,2,-1]],[0,2],[2,5],[0,5]]'
#
# 给定一个整数数组 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 方法。
#
#
#
# @lc code=start
class NumArray(object):
def __init__(self, nums):
"""
:type nums: List[int]
"""
n=len(nums)
self.sums=[0]*n
for i in range(n):
self.sums[i]=self.sums[i-1]+nums[i]
def sumRange(self, i, j):
"""
:type i: int
:type j: int
:rtype: int
"""
if i==0:return self.sums[j]
return self.sums[j]-self.sums[i-1]
# Your NumArray object will be instantiated and called as such:
# obj = NumArray(nums)
# param_1 = obj.sumRange(i,j)
# @lc code=end