LeetCode_Range Sum Query - Immutable
2015-11-13 20:19
369 查看
Given an integer array nums, find the sum of the elements between indicesi and
j (i ≤ j), inclusive.
Example:
Note:
You may assume that the array does not change.
There are many calls to sumRange function.
解题思路:此题从字面上看并不难,只要找出数组中对应索引位置,并计算从0-index的和并做对应索引的减法即可,但是注意题目中的Note可以发现,你的方法可能会被大量的调用,所以每次调用都去做运算是不合适的,必将出现Time Limited Exceeded。所以需要在类构造时,便需要准备一些结果集(所有索引到0的和),以便在后面的运算中减少计算量。
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-index的和并做对应索引的减法即可,但是注意题目中的Note可以发现,你的方法可能会被大量的调用,所以每次调用都去做运算是不合适的,必将出现Time Limited Exceeded。所以需要在类构造时,便需要准备一些结果集(所有索引到0的和),以便在后面的运算中减少计算量。
public class NumArray { private int[] mArr = null; private int[] mResults = null; // 3ms public NumArray(int[] nums) { mArr = nums; mResults = new int[mArr.length]; for (int i = 0; i < mArr.length; i++) { if (i == 0) { mResults[0] = mArr[0]; } else { mResults[i] = mResults[i - 1] + mArr[i]; } } } public int sumRange(int i, int j) { if (mArr == null || mArr.length - 1 < i || mArr.length - 1 < j || i < 0 || j < 0) { return 0; } int result = i <= 0 ? mResults[j] : (mResults[j] - mResults[i - 1]); return result; } public static void main(String[] args) { int[] nums = { -2, 0, 3, -5, 2, -1 }; // sumRange(0, 2) -> 1 // sumRange(2, 5) -> -1 // sumRange(0, 5) -> -3 NumArray numArray = new NumArray(nums); numArray.sumRange(0, 2); numArray.sumRange(2, 5); numArray.sumRange(0, 5); } }
相关文章推荐
- LeetCode_Range Sum Query 2D - Immutable
- easyui动态添加文本域
- UINavigationItem UINavigationBar分析
- [leetcode-304]Range Sum Query 2D - Immutable
- tableViewCell的不同高度创建
- UI第四天:事件处理
- 分别使用Jmeter/Loadrunner/SoapUI做Web Service接口测试的简单操作
- 问题:-[UIViewController _loadViewFromNibNamed:bundle:] loaded the "BlueView" nib but the view outlet was not set.
- 111 AddressBookUI
- 根据输入的起止日期判断天数,strtotime,数据的去重和array_keys,array_values函数
- 用Fragment制作的Tab页面产生的UI重叠问题
- 【leetcode】【62】Unique Paths
- 安卓UI开发基础-View
- IE浏览器中 $.ajax返回uindefined 其他浏览器正常
- shuxue
- zuihao
- Testing Round #12 C Subsequences
- 导航条UINavigationBar和工具栏tabBar的灰色高亮线去掉
- [JS]EASYUI组件的程序基本结构
- UIDataPicker 时间选择器