【leetcode】303. 区域和检索 - 数组不可变
作者:互联网
题目:303. 区域和检索 - 数组不可变 - 力扣(LeetCode) (leetcode-cn.com)
思路1:
直接遍历数组,对题干给出范围的数值累加
代码如下:
class NumArray { private int[] nums; public NumArray(int[] nums) { this.nums = nums; } public int sumRange(int left, int right) { int res = 0; for(int i=left;left<=right;i++){ res = res + nums[left]; } return res; } } /** * Your NumArray object will be instantiated and called as such: * NumArray obj = new NumArray(nums); * int param_1 = obj.sumRange(left,right); */
但是这种方法sumRange的时间复杂度为O(N),对于频繁调用sumRange函数来说,效率低下。
怎么将sumRange
函数的时间复杂度降为 O(1)
,说白了就是不要在 sumRange
里面用 for 循环
思路2:
对于上面,可以利用前缀和将 sumRange
函数的时间复杂度降为 O(1)
声明一个前缀和数组presum[i]的值表示数组前i个元素之和,初始presum[0]=0;
class NumArray { // 前缀和数组 private int[] preSum; /** 构造前缀和 */ public NumArray(int[] nums) { preSum = new int[nums.length+1]; preSum[0] = 0; for(int i=1;i<preSum.length;i++){ preSum[i] = preSum[i-1]+nums[i-1]; } } /* 查询闭区间 [left, right] 的累加和 */ public int sumRange(int left, int right) { return preSum[right+1]-preSum[left]; } } /** * Your NumArray object will be instantiated and called as such: * NumArray obj = new NumArray(nums); * int param_1 = obj.sumRange(left,right); */
标签:检索,前缀,nums,int,303,NumArray,数组,sumRange,leetcode 来源: https://www.cnblogs.com/xiangshigang/p/16215898.html