【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);
 */
复制代码

 

posted @   MintMin  阅读(34)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 终于写完轮子一部分:tcp代理 了,记录一下
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
点击右上角即可分享
微信分享提示