首页 > 其他 > 详细

303. Range Sum Query - Immutable

时间:2015-12-16 09:23:49      阅读:151      评论:0      收藏:0      [点我收藏+]

题目:

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);

 

Reference:

 

303. Range Sum Query - Immutable

原文:http://www.cnblogs.com/yrbbest/p/5050025.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!