LeetCode:Range Sum Query - Immutable - 数组指定区间内的元素和

1、题目名称

Range Sum Query(数组指定区间内的元素和)

2、题目地址

https://leetcode.com/problems/range-sum-query-immutable/

3、题目内容

英文:Given an integer array nums, find the sum of the elements between indices i and j (ij), inclusive.

中文:给定一个数组nums,求出索引i和j之间元素的和,i一定是小于或等于j的

例如:

Given nums = [-2, 0, 3, -5, 2, -1]

sumRange(0, 2) -> 1
sumRange(2, 5) -> -1
sumRange(0, 5) -> -3

注意:你可以假定数组不会发生变化,sumRange函数会被调用多次

4、解题方法

不同于其他题目以Solution为类名,本题中给出的类名为NumArray,并且里面有两个函数。第一个函数为构造函数,第二个函数为sumRange,这两个函数都是我们要实现的函数。

题目给出的代码结构如下:

public class NumArray {

    public NumArray(int[] nums) {
        
    }

    public int sumRange(int i, int j) {
        
    }
}


// Your NumArray object will be instantiated and called as such:
// NumArray numArray = new NumArray(nums);
// numArray.sumRange(0, 1);
// numArray.sumRange(1, 2);

在本题中,sumRange可能会被调用多次,因此采用下面这种方式是不明智的(会导致TLE):

public class NumArray {

    public int[] nums;

    public NumArray(int[] nums) {
        this.nums = nums;
    }

    public int sumRange(int i, int j) {
        int result = 0;
        for (int counter = i; counter <= j; counter++) {
            result += nums[counter];
        }
        return result;
    }
}

如果我们换一种思路,在构造函数内就计算了从第一个元素到当前元素所有元素的和,保存到数组sums的对应位置中,在函数sumRange中就可以很方便地算出题目中要求的结果了。

Java代码如下:

/**
 * @功能说明:LeetCode 303 - Range Sum Query - Immutable
 * @开发人员:Tsybius2014
 * @开发时间:2015年11月10日
 */
public class NumArray {

    public int[] sums;

    public NumArray(int[] nums) {
        if (nums == null) {
            sums = null;
        } else if (nums.length == 0) {
            sums = new int[0];
        } else {
            this.sums = new int[nums.length];
            sums[0] = nums[0];
            for (int i = 1; i < nums.length; i++) {
                sums[i] = sums[i - 1] + nums[i];
            }
        }
    }

    public int sumRange(int i, int j) {
        if (sums == null) {
            return 0;
        }
        if (i >= sums.length || j >= sums.length || i > j) {
            return 0;
        } else if (i == 0) {
            return sums[j];
        } else {
            return sums[j] - sums[i - 1];
        }
    }
}

END

转载于:https://my.oschina.net/Tsybius2014/blog/528708

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值