leetcode(58)-Range Sum Query - Immutable
来源:互联网 发布:基于云计算的oracle 编辑:程序博客网 时间:2024/06/08 14:30
题目:
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) -> 1sumRange(2, 5) -> -1sumRange(0, 5) -> -3Note:You may assume that the array does not change.There are many calls to sumRange function.
思路:
- 题意:要求给定坐标区间的数组的和,题目要求是大量的使用,所以需要构造缓存,构造缓存的方法就是记录,把num[i~j]的和,变为num[0~j]-num[0~i],这样就是缓存了一个长度为length的和
代码:
public class NumArray { private int[] num = null; public NumArray(int[] nums) { int all = 0; num = new int[nums.length]; for(int i = 0; i < nums.length;i++){ all = all+nums[i]; num[i] = all; } } public int sumRange(int i, int j) { return i == 0 ? num[j]: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);
0 0
- leetcode(58)-Range Sum Query - Immutable
- [LeetCode] Range Sum Query - Immutable
- [LeetCode]Range Sum Query - Immutable
- LeetCode Range Sum Query - Immutable
- LeetCode Range Sum Query - Immutable
- LeetCode:Range Sum Query - Immutable
- [Leetcode]Range Sum Query - Immutable
- leetcode Range Sum Query - Immutable
- leetcode- Range Sum Query - Immutable
- leetcode:Range Sum Query - Immutable
- Leetcode: Range Sum Query - Immutable
- Leetcode: Range Sum Query - Immutable
- 【leetcode】:Range Sum Query - Immutable
- leetcode--Range Sum Query - Immutable
- LeetCode Range Sum Query - Immutable
- LeetCode|Range Sum Query - Immutable
- LeetCode:Range Sum Query - Immutable
- 【Leetcode】Range Sum Query - Immutable
- 淘宝滑动验证码研究
- LeetCode 12. Integer to Roman
- 关于证书笔记
- JAVA实现链表
- 策略模式
- leetcode(58)-Range Sum Query - Immutable
- AngularJS 知识总结
- vb13
- Windows 7(Win7)下Visual Studio 2012(VS2012)编译jrtplib与MinGW编译jrtplib
- TensorFlow0.7 的安装
- 开源控件GifView
- VB程序语言1
- 【JS】:JS实现页面反向显示
- Android活动的四种启动方式(standard singleTop singleTask singleInstance)