[leetcode]303. Range Sum Query - Immutable

来源:互联网 发布:新日铁软件 张涛 编辑:程序博客网 时间:2024/06/07 05:08

Given an integer array nums, find the sum of the elements between indicesi and j (ij), inclusive.

Example:

Given nums = [-2, 0, 3, -5, 2, -1]sumRange(0, 2) -> 1sumRange(2, 5) -> -1sumRange(0, 5) -> -3

Note:

  1. You may assume that the array does not change.
  2. There are many calls to sumRange function.

思路:由于要多次调用sumRange()方法,所以不能每次在sumRange里计算数组的和,应该在构造方法里就将数组的和计算好。

public class NumArray {  private int[] sums;         public NumArray(int[] nums) {if (nums == null) {sums = null;} else if (nums.length == 0) {sums = new int[] { 0 };} else {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];}}}// Your NumArray object will be instantiated and called as such:// NumArray numArray = new NumArray(nums);// numArray.sumRange(0, 1);// numArray.sumRange(1, 2);


不能用如下的方法,会导致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;    }}


1 0
原创粉丝点击