Java [Leetcode 303]Range Sum Query - Immutable
2016-02-18 21:58
465 查看
题目描述:
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.
解题思路:
如代码所示。
代码如下:
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.
解题思路:
如代码所示。
代码如下:
public class NumArray { int[] nums; public NumArray(int[] nums) { for(int i = 1; i < nums.length; i++){ nums[i] += nums[i - 1]; } this.nums = nums; } public int sumRange(int i, int j) { if(i == 0) return nums[j]; return nums[j] - nums[i - 1]; } } // Your NumArray object will be instantiated and called as such: // NumArray numArray = new NumArray(nums); // numArray.sumRange(0, 1); // numArray.sumRange(1, 2);
相关文章推荐
- Queue and stack
- UILabel添加删除线,类似团购效果
- SPOJ DQUERY树状数组离线or主席树
- JDBC连接池、监控组件 Druid
- SPOJ DQUERY树状数组离线or主席树
- EasyUI系列学习(五)-Resizable(调整大小)
- Swagger UI 使用
- 分层模型的典型应用和FishiGUI的分层模型
- 4.跟我学solr---SolrRequestHandler具体解释
- 不错的判断 UITextView 内容不超过20个字符串的方法
- JS模块化工具requirejs
- Building Android notifications 2.3 through to 6.0
- Handler官方范例AsyncQueryHandler源码解析
- EasyUI系列学习(四)-Droppable(放置)
- org.hibernate.QueryException: query must begin with SELECT or FROM: delete
- ASTQueryTranslatorFactory weblogic10.3 org.hibernate.hql.ast.HqlToken报错问题
- Huawei Quidway S3900 stp与锐捷不兼容问题
- error:no such partition.grub rescue>问题
- iOS-UI-基本控件之UILabel
- UITextField限制汉字数量最正确的姿势,解决iOS7下substringToIndex方法导致的崩溃