【leetcode题解】[E][52]303. Range Sum Query - Immutable
2015-12-23 21:41
489 查看
Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive.
Example:
Note:
You may assume that the array does not change.
There are many calls to sumRange function.
Subscribe to see which companies asked this question
就是实现数据结构的动态规划。分别用left和right保存从左、从右算起的和,然后用总和减去左右就是中间的
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.
Subscribe to see which companies asked this question
就是实现数据结构的动态规划。分别用left和right保存从左、从右算起的和,然后用总和减去左右就是中间的
class NumArray(object): def __init__(self, nums): if nums == []: return self.nums = nums self.total = sum(nums) self.left = [0]*len(nums) self.right = [0]*len(nums) #self.left[0] = nums[0] for i in xrange(1,len(nums)): self.left[i] = self.left[i-1] + nums[i-1] #print i,self.left[i] for i in xrange(len(nums)-2,-1,-1): self.right[i] = self.right[i+1] + nums[i+1] #print i,self.right[i] """ initialize your data structure here. :type nums: List[int] """ def sumRange(self, i, j): #print self.left #print 'right',self.right return self.total - self.left[i] - self.right[j] """ sum of elements nums[i..j], inclusive. :type i: int :type j: int :rtype: int """ # Your NumArray object will be instantiated and called as such: # numArray = NumArray(nums) # numArray.sumRange(0, 1) # numArray.sumRange(1, 2)
相关文章推荐
- TimesTen_创建序列(sequence)
- UICollectionViewCell
- UI01_UILabel
- 基于duilib的多标签简易浏览器
- UIView
- com.mysql.jdbc.MysqlDataTruncation: Data truncation: Incorrect datetime value: '' for column 'rdate'
- 利用 druid 解析器解析SQL
- android125 zhihuibeijing 缓存
- leetcode -- Distinct Subsequences -- DP重点
- leetcode刷题日记——Implement Stack using Queues
- 三大GUI库——AWT、swing、SWT
- Android之UI圆角矩形,图形圆角美化
- 超级简单的UGUI血条制作技巧
- 关于easyUI在子页面增加显示tabs的一个问题
- KVO(NSKeyValueObserving)
- EasyUI Datebox 日期框
- UITableView 视觉差效果
- 在NSString NSNumber NSValue 中一些基本方法的使用和解释
- Material Design UI Widgets
- UITableViewController