• LeetCode -- Range Sum Query


    geQuestion:

    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:

    1. You may assume that the array does not change.
    2. 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);
  • 相关阅读:
    Linux Apache安装加载mod_deflate模块
    Ubuntu配置apache2.4配置虚拟主机遇到的问题
    Apache启用GZIP压缩网页传输方法
    apache高负载性能调优
    在Linux系统上查看Apache服务器的错误日志
    Ubuntu Apache配置及开启mod_rewrite模块
    APACHE支持.htaccess
    apache 虚拟主机详细配置:http.conf配置详解
    ASP.NET WEB项目文件夹上传下载解决方案
    JAVA WEB项目文件夹上传下载解决方案
  • 原文地址:https://www.cnblogs.com/little-YTMM/p/5188699.html
Copyright © 2020-2023  润新知