LeetCode -- Range Sum Query
2016-02-14 09:53
441 查看
geQuestion:
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.
Analysis:
给出一个整数数组,得出i与j之间的数字之和(i<=j)。你可以假设数组不会改变,并且他们可以调用多次sunRange函数。
Answer:
解法一:
解法二:由于题目中说会多次调用该函数,计算某个区间内的和,如果按照上面的解法,当数组过大时,会导致多次重复计算和,因此我们可以想办法存储中间计算的结果来简化计算。 方法就是一次存储从第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.
Analysis:
给出一个整数数组,得出i与j之间的数字之和(i<=j)。你可以假设数组不会改变,并且他们可以调用多次sunRange函数。
Answer:
解法一:
public class NumArray { int[] num; public NumArray(int[] nums) { this.num = nums; } public int sumRange(int i, int j) { int res = 0; for(int k=i; k<j+1; k++) { res += num[k]; } return res; } } // Your NumArray object will be instantiated and called as such: // NumArray numArray = new NumArray(nums); // numArray.sumRange(0, 1); // numArray.sumRange(1, 2);
解法二:由于题目中说会多次调用该函数,计算某个区间内的和,如果按照上面的解法,当数组过大时,会导致多次重复计算和,因此我们可以想办法存储中间计算的结果来简化计算。 方法就是一次存储从第0个元素到第i个元素计算的中间结果,当求某个区间的和时,直接用大区间减去小区间的和即可。
public class NumArray { int[] num; public NumArray(int[] nums) { if(nums == null) num = null; else if(nums.length == 0) num = nums; else { num = new int[nums.length]; num[0] = nums[0]; for(int i=1; i<nums.length; i++) { num[i] = nums[i] + num[i-1]; } for(int i=0; i<num.length; i++) System.out.print(num[i] + " * "); System.out.println(); } } public int sumRange(int i, int j) { if(i == 0) return num[j]; else return num[j] - num[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);
相关文章推荐
- Adafruit的樹莓派教程第一課福利:做一個備份鏡像
- 極客范 – GeekFan.net | Adafruit的樹莓派教程第一課:為你的樹莓派准備一張SD卡 - 極客范 - GeekFan.net 极客范 – GeekFan.net 首頁 科技資訊 硬件
- iOS之UIImage性能
- 1041. Be Unique (20)
- CodeForces 625A Guest From the Past
- 禁止UITextField 使用粘贴复制功能
- UIStackView相关
- LeetCode 62. Unique Paths
- 浅谈交互设计师要知道的「数据分析」两三事
- Code Contracts 关于方法Contract.Requires<T>()
- UI基础-04 简单的加法计算器
- UIScrollView
- Splunk setup guide
- ViewPager中requestDisallowInterceptTouchEvent
- LeetCode 303. Range Sum Query - Immutable
- iOS --- 根据字符串的实际大小来计算UILabel的size
- 自定义UICollectinviewFlowLayout,即实现瀑布流
- Bluestacks2查看/data/data下文件的方法
- ANDROID 6.0大舞台(1):从交互设计到UI代码开发
- Arduino代码机制-引脚读写