LeetCode-Range Sum Query - Immutable

Description:

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.

题目大意:给定一个数组和两个下标i,j,求出i和j之间的数字的和。包含i,j。

思路:这题非常简单,按照最简单的思路做,就是循环i到j求和。

实现代码:

public class NumArray {
    
    private int[] nums;

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

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


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

但是这样就没意思了,后台的调用方式是连续调用一个数组的sumRange方法。但是上面的解法就会有非常多的重复计算。所以还可以优化,就是在初始化的时候把所有的和都算出来,在返回的时候直接获取就行了。用sum[i]表示0~i的和,则i~j的和就是sum[j] - sum[i-1]。nums为空,i=0,等情况要特殊考虑。

实现代码:

public class NumArray {
    
    private int[] nums;
    
    private int[] sums;

    public NumArray(int[] nums) {
        if(nums != null) {
            this.nums = nums;
        }
        else
            this.nums = new int[0];
        sums = new int[nums.length];
        if(nums.length != 0)
            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(nums == null || nums.length == 0) return 0;
        if(i == 0) return sums[j];
        return sums[j] - sums[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);

效率明显提高了。

posted @ 2016-02-22 18:24  Pickle  阅读(336)  评论(0编辑  收藏  举报