303. Range Sum Query - Immutable

题目:

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.

链接: http://leetcode.com/problems/range-sum-query-immutable/

题解:

给定数组,求range之内的数组和。 我们可以新建一个dp数组来保存数据,dp[i]表示 0到i-1这i个数的sum,每次我们就可以在使用O(n)初始化之后,用O(1)的时间得到搜索结果了。

Time Complexity - O(n), Space Compleixty - O(1)。

public class NumArray {
    private int[] sum;
    
    public NumArray(int[] nums) {
        sum = new int[nums.length + 1];
        
        for(int i = 1; i < sum.length; i++) {
            sum[i] = nums[i - 1] + sum[i - 1] ; 
        }
    }

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


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

 

二刷:

方法和一刷一样,新建一个数组来保存sum。注意边界条件。

Java:

public class NumArray {
    private int[] sums;

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

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


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

 

三刷:

跟上面一样。注意创建dp数组的时候我们增加1个长度,然后从1开始遍历,可以简化一些代码。 面试的时候还需要写明边界条件,比如i 和 j越界的情况。

Java:

public class NumArray {
    private int[] sums;
    
    public NumArray(int[] nums) {
        sums = new int[nums.length + 1];
        for (int i = 1; i <= nums.length; i++) {
            sums[i] = sums[i - 1] + nums[i - 1];
        }
    }

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


// Your NumArray object will be instantiated and called as such:
// NumArray numArray = new NumArray(nums);
// numArray.sumRange(0, 1);
// numArray.sumRange(1, 2);
public class NumArray {
    private int[] sums;
    
    public NumArray(int[] nums) {
        this.sums = new int[nums.length + 1];
        for (int i = 0; i < nums.length; i++) {
            sums[i + 1] = sums[i] + nums[i];
        }
    }

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


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

 

 

 

Reference:

 

posted @ 2015-12-16 04:43  YRB  阅读(1152)  评论(0编辑  收藏  举报