LeetCode 303. Range Sum Query - Immutable(数组求和)
2016-04-19 07:21
429 查看
原题网址:https://leetcode.com/problems/range-sum-query-immutable/
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.
方法:保存数组从0~i的累加值。
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.
方法:保存数组从0~i的累加值。
public class NumArray { private int[] sums; public NumArray(int[] nums) { sums = new int[nums.length]; for(int i=0; i<nums.length; i++) { if (i==0) sums[i] = nums[i]; else sums[i] = sums[i-1] + nums[i]; } } public int sumRange(int i, int j) { if (i==0) return sums[j]; return sums[j]-sums[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);
相关文章推荐
- 常用到的一个辅助表 master..spt_values
- 5种 (UI线程与后台线程交互设计的方法)
- requestWindowFeature
- 上传JSON数据时,url变空,JSON数据不能拼接在url中,需单独放在请求的参数中作为一个整体的value上传
- NOJ 1925 sequence
- uikeyboard所在uiwindow
- 外循环与内循环的分析演示
- poj 1986 Distance Queries 带权lca 模版题
- -[UIKBBlurredKeyView candidateList]: unrecognized
- Qt中用户界面的User Interface Compiler(uic)机制的相关说明
- UILocalNotification 开发过程中的使用
- UI组件——GridLayout
- BuildActionExecuter Error
- POJ 1679 The Unique MST【暴力求次小生成树】
- Java之UUID介绍
- javaEE--request.getRequestDispatcher--URL后带参数实现自定义跳转
- xib自定义UIView报错误 "forUndefinedKey:]: this class is not key value coding-compliant for the key"
- Java之UUID生成
- Android值动画二(ValueAnimator)
- iOS黄色警告之was built for newer iOS version (7.0) than being linked (6.0)解决办法