LeetCode 303 Range Sum Query - Immutable
2016-03-31 15:37
549 查看
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.
话不多说,直接看答案吧。参考了/article/7966850.html
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.
话不多说,直接看答案吧。参考了/article/7966850.html
class NumArray { int[] sums; public NumArray(int[] nums) { sums = new int[nums.length]; System.arraycopy(nums, 0, sums, 0, nums.length); for (int i = 1; i < nums.length; i++) sums[i] = sums[i - 1] + nums[i]; } public int sumRange(int i, int j) { if (i < 0 || j < 0 || i >= sums.length || j >= sums.length) return 0; return i == 0 ? sums[j] : sums[j] - sums[i - 1]; } }
相关文章推荐
- Java GUI 画点
- 【hdu1242】Rescue——bfs+小根堆
- QML QuickItem鼠标键盘处理
- sql自动uuid,导表exp,imp指令
- EasyUI——DateBox和DateTimeBox的汉化和显示格式修改
- 96. Unique Binary Search Trees
- 回归基础系列-call by value / call by reference区别与实例
- LValue RValue
- hdu 2604 Queuing【递推+矩阵快速幂】
- ${pageContext.request.contextPath} JSP路径问题
- 多线程实现Thread.Start()与ThreadPool.QueueUserWorkItem两种方式对比
- YTKKeyValueStore用法
- 【poj 1019】Number Sequence
- Java中的String、StringBuffer和StringBuilder区别
- GCD的同步异步串行并行、NSOperation和NSOperationQueue一级用dispatch_once实现单例
- [Form Builder]:CREATE_GROUP Built-in
- 并发队列ConcurrentLinkedQueue和阻塞队列LinkedBlockingQueue用法
- String.valueOf()的一个坑—“null”
- 对Map类分别按照Key,Value排序,返回值为List对象
- iOS之NSPredicate(正则表达式和UIBarController)