区域和检索 - 数组不可变

2019-04-20  本文已影响0人  xin激流勇进
给定 nums = [-2, 0, 3, -5, 2, -1],求和函数为 sumRange()

sumRange(0, 2) -> 1
sumRange(2, 5) -> -1
sumRange(0, 5) -> -3
package structures;

class NumArray {

    private int[] sum;

    public NumArray(int[] nums) {
        if (nums.length > 0) {
            sum = new int[nums.length + 1];
            // 0表示一个元素也没有 2表示两个元素的和
            sum[0] = 0;
            for (int i = 1; i < nums.length; i++) {
                sum[i] = sum[i - 1] + nums[i - 1];
            }
        }
    }

    public int sumRange(int i, int j) {
        return sum[j + 1] - sum[i];
    }

    public static void main(String[] args) {
        int[] nums = {-2, 0, 3, -5, 2, -1};
        NumArray obj = new NumArray(nums);
        int param_1 = obj.sumRange(1, 4);
        System.out.println(param_1);
    }
}

/**
 * Your NumArray object will be instantiated and called as such:
 * NumArray obj = new NumArray(nums);
 * int param_1 = obj.sumRange(i,j);
 */
package structures;

class NumArray {

    private int[] sum;

    public NumArray(int[] nums) {
        if (nums.length > 0) {
            sum = new int[nums.length + 1];
            // 0表示一个元素也没有 2表示两个元素的和
            sum[0] = 0;
            for (int i = 1; i < nums.length; i++) {
                sum[i] = sum[i - 1] + nums[i - 1];
            }
        }
    }

    public int sumRange(int i, int j) {
        return sum[j + 1] - sum[i];
    }

    public static void main(String[] args) {
        int[] nums = {-2, 0, 3, -5, 2, -1};
        NumArray obj = new NumArray(nums);
        int param_1 = obj.sumRange(1, 4);
        System.out.println(param_1);
    }
}

/**
 * Your NumArray object will be instantiated and called as such:
 * NumArray obj = new NumArray(nums);
 * int param_1 = obj.sumRange(i,j);
 */
上一篇下一篇

猜你喜欢

热点阅读