Range Sum Query - Immutable
2016-07-25 11:59
489 查看
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.
Hide Company Tags
解法一:
O(1) init, O(n) query
解法二:
O(n) init, O(1) query
reference: https://discuss.leetcode.com/topic/29194/java-simple-o-n-init-and-o-1-query-solution
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.
Hide Company Tags
解法一:
O(1) init, O(n) query
public class NumArray { private int[] nums; private int sum; public NumArray(int[] nums) { this.nums = nums; this.sum = 0; } public int sumRange(int i, int j) { sum = 0; //保证immutable for(int k = i;k<=j;k++) { sum = sum + nums[k]; } return sum; } } // Your NumArray object will be instantiated and called as such: // NumArray numArray = new NumArray(nums); // numArray.sumRange(0, 1); // numArray.sumRange(1, 2);
解法二:
O(n) init, O(1) query
public class NumArray { int[] nums; public NumArray(int[] nums) { for(int i = 1; i < nums.length; i++) nums[i] += nums[i - 1]; this.nums = nums; } public int sumRange(int i, int j) { if(i == 0) return nums[j]; return nums[j] - nums[i - 1]; } }
reference: https://discuss.leetcode.com/topic/29194/java-simple-o-n-init-and-o-1-query-solution
相关文章推荐
- UIScrollViewDelegate Protocol Reference
- 64.Which two statements are true about setting the FAST_START_MTTR_TARGET initialization parameter t
- Sustainability through Energy Load Shaping for Buildings using R
- longestIncreasingSequence最长上升子序列问题
- 63.Examine the values for the following initialization parameters: FAST_START_MTTR_TARGET = 0 LOG_CH
- UIScrollView Class Reference
- CUICatalog: Invalid asset name supplied:
- Camstar Portal modeling user guid --自定义用户菜单
- Could not connect to SMTP host,PKIX path building failed,unable to find valid certification path...
- luigi学习1
- Android子线程居然可以更新UI?
- javaGUI学习——在面板上画一张图片
- soapui工具 简单使用
- HDU 5749 BestCoder Round #84 Colmerauer(暴力贡献)
- HDU1711 Number Sequence KMP基础
- easyui的validatebox
- Drawable 下定义一个会旋转的ui
- warning: escape sequence 'u' is not valid. see 'help sprintf' for valid escape sequences._
- Qt中forward declaration of struct Ui::xxx的解决
- Guess Number Higher or Lower && 九章二分法模板