107.Range Sum Query - Immutable
2016-04-10 09:59
369 查看
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.
Subscribe to see which companies asked this question.
分析:题目意思是给定一个数组,然后多次给定一个下标返回,求返回这个范围的元素和。
因为题目中说到会多次调用这个方法,所以在初始化NumArray这个对象的时候就把这个数组sums给初始化好,sums的第i个元素表示nums元素中的[0,i]的和。
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.
Subscribe to see which companies asked this question.
分析:题目意思是给定一个数组,然后多次给定一个下标返回,求返回这个范围的元素和。
因为题目中说到会多次调用这个方法,所以在初始化NumArray这个对象的时候就把这个数组sums给初始化好,sums的第i个元素表示nums元素中的[0,i]的和。
/**@date 20160410*/ public class NumArray { /*定义一个数组对应下标为i的元素存储nums中下标为0到i项的和。*/ int[] sums; int len;//存储数组的长度 public NumArray(int[] nums) { len = nums.length;/*!!!!!!!!!!!!!!!!!!!注意之前一直不通过的原因是在这个len 前面又加了int,导致整个对象的成员变量len的值为0*/ sums = new int[len]; /*初始化sums的值*/ if(len<=0){ sums = new int[0]; }else{ sums[0] = nums[0]; for(int i=1;i<len;i++){ sums[i]=sums[i-1]+nums[i]; } } } /*求数组nums中下标i到下标j的和,直接计算sums[j]-sums[i-1](前提是i>=1,如果i=0,则直接返回sums[j])*/ public int sumRange(int i, int j) { /*保证j和i不能越界*/ if(j>=len){ j=len-1; } if(i<=0){ return sums[j]; }else{ return sums[j]-sums[i-1]; } } }
相关文章推荐
- WPF 绑定中的TargetNullValue
- fuelux.tree用法
- [C#] C# Concepts: Value vs Reference Types
- 仿华为系统自带天气预报UI---线条圆圈控件
- (转)如何修复ubuntu的UEFI引导
- Qt的Script、Quick、QML的关系与总结
- [x-Code7新功能之二]UIAlertController的练习
- map key value的排序问题
- [091127]Dark Blue幽深之蓝【汉化硬盘版】[带全CG存档&攻略+日文原版文件]
- OS开发UI篇—UITabBarController简单介绍
- UI测试
- js模块化之require.js
- UI调试神器 for ios:Reveal的使用与破解
- invalid bundle ipad multitasking support requires launch story board in bundle ...
- required opengl extension,please update your opengl driver
- 用UIButton的类方法ButtonWithType创建时调用的是initWithFrame方法
- 轻量级应用开发之(08)UITableView
- 特殊权限
- druid 数据库密码加密
- 在Android value中添加颜色resource文件