[leetcode]303. Range Sum Query - Immutable
来源:互联网 发布:新日铁软件 张涛 编辑:程序博客网 时间:2024/06/07 05:08
Given an integer array nums, find the sum of the elements between indicesi and j (i ≤ j), inclusive.
Example:
Given nums = [-2, 0, 3, -5, 2, -1]sumRange(0, 2) -> 1sumRange(2, 5) -> -1sumRange(0, 5) -> -3
Note:
- You may assume that the array does not change.
- There are many calls to sumRange function.
思路:由于要多次调用sumRange()方法,所以不能每次在sumRange里计算数组的和,应该在构造方法里就将数组的和计算好。
public class NumArray { private int[] sums; public NumArray(int[] nums) {if (nums == null) {sums = null;} else if (nums.length == 0) {sums = new int[] { 0 };} else {sums = new int[nums.length];sums[0] = nums[0];for (int i = 1; i < nums.length; i++) {sums[i] = sums[i - 1] + nums[i];}} }public int sumRange(int i, int j) {if (sums == null) {return 0;}if (i >= sums.length || j >= sums.length || i > j) {return 0;} else if (i == 0) {return sums[j];} else {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);
不能用如下的方法,会导致TLE
public class NumArray { public int[] nums; public NumArray(int[] nums) { this.nums = nums; } public int sumRange(int i, int j) { int result = 0; for (int counter = i; counter <= j; counter++) { result += nums[counter]; } return result; }}
1 0
- <LeetCode OJ> 303. Range Sum Query - Immutable
- leetcode 303. Range Sum Query - Immutable
- [leetcode] 303. Range Sum Query - Immutable
- 303. Range Sum Query - Immutable [Leetcode]
- 303. Range Sum Query - Immutable LeetCode
- [Leetcode]303. Range Sum Query - Immutable
- Leetcode:303. Range Sum Query - Immutable(JAVA)
- LeetCode 303. Range Sum Query - Immutable
- LeetCode.303.Range Sum Query - Immutable
- LeetCode *** 303. Range Sum Query - Immutable
- LeetCode 303. Range Sum Query - Immutable
- leetcode-303. Range Sum Query - Immutable
- LeetCode-303.Range Sum Query - Immutable
- Leetcode 303. Range Sum Query - Immutable
- 【leetcode】303. Range Sum Query - Immutable
- [Leetcode]303. Range Sum Query - Immutable
- Leetcode题解 303. Range Sum Query - Immutable
- LeetCode - 303. Range Sum Query - Immutable
- 夕拾算法初级篇:1)1001. 害死人不偿命的(3n+1)猜想
- unity播放加密的音频文件
- 学习bootstrap 总结(1)
- copy构造函数调用时机4,函数返回值是匿名对象
- AngularJS启动过程
- [leetcode]303. Range Sum Query - Immutable
- 单向链表的建议搭建
- 进程的组成部分
- Python将多个list合并为1个list
- hdu2036 计算坐标内任意多边形的面积 含凹凸
- 3D扫雷
- 压缩表
- 网站建设需要掌握的内容
- Ajax onreadystatechange