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

一、题目名称java

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

二、题目地址函数

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

三、题目内容code

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

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

例如:leetcode

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

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

注意:你能够假定数组不会发生变化,sumRange函数会被调用屡次开发

四、解题方法get

不一样于其余题目以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

相关文章
相关标签/搜索