Leetcode: Range Sum Query - Immutable
2015-12-30 10:45
603 查看
Question
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.
Hide Tags Dynamic Programming
Hide Similar Problems (M) Range Sum Query 2D - Immutable (M) Range Sum Query - Mutable
My Solution
Accept[code]class NumArray(object): def __init__(self, nums): """ initialize your data structure here. :type nums: List[int] """ if len(nums)!=0: self.sum = [0]*len(nums) self.sum[0] = nums[0] for ind in range(1,len(nums)): self.sum[ind] = self.sum[ind-1] + nums[ind] else: self.sum = -1 def sumRange(self, i, j): """ sum of elements nums[i..j], inclusive. :type i: int :type j: int :rtype: int """ if i>j or self.sum==-1: return 0 if i==0: return self.sum[j] return self.sum[j] - self.sum[i-1] # Your NumArray object will be instantiated and called as such: # numArray = NumArray(nums) # numArray.sumRange(0, 1) # numArray.sumRange(1, 2)
相关文章推荐
- 黑马程序员--OC自学笔记---10Foundation、NSFileManager、iOS沙盒、OC结构体、NSNumber、NSValue、NSDate、copy、单例模式
- Leetcode: Range Sum Query 2D - Immutable
- UIControl的介绍和使用
- CALayer与UIView的关系
- UpdateData(TRUE)和UpdateData(FALSE)的区别
- java.sql.SQLException:Column count doesn't match value count at row 1
- iOS 通过HEX(十六进制)得到一个UIColor的对象
- 虚拟环境下使用fuel安装部署opesntack
- UGUI中Button和Toggle 添加动态事件
- 在一个UILabel的文字采用不同的字体样式和字体大小
- UISwitch详解
- beginUpdates和endUpdates-实现UITableView的动画块
- MiniUI——TreeGrid懒加载
- easyui中 在子tabs中 添加新的tabs
- startActivity时报错Calling startActivity() from outside of an Activity context requires the FLAG_ACTIVI
- vue.js学习
- EasyUI datagrid detailview
- The project was not built since its build path is incomplete.
- UIStepper详解
- codeforces 612C Replace To Make Regular Bracket Sequence