155.Range Sum Query - Immutable(范围总和查询 - 不可变)

题目:

Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive.

给定整数数组nums,找到索引i和j(i≤j)之间的元素之和,包括端点。

Example:

Given nums = [-2, 0, 3, -5, 2, -1]
给定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. sumRange函数有很多调用。

解答:

时间复杂度:O(n)初始化   O(1)查询效率

 1 class NumArray {
 2     
 3     int[] nums;
 4 
 5     public NumArray(int[] nums) {
 6         for(int i=1;i<nums.length;i++)
 7             nums[i]+=nums[i-1];
 8         this.nums=nums;
 9     }
10     
11     public int sumRange(int i, int j) {
12         if(i==0)
13             return nums[j];
14         return nums[j]-nums[i-1];
15     }
16 }
17 
18 /**
19  * Your NumArray object will be instantiated and called as such:
20  * NumArray obj = new NumArray(nums);
21  * int param_1 = obj.sumRange(i,j);
22  */

详解:

将数组每一项赋值为从第0项开始到该项的和

sum[i,j]=sum[0,i-1]+sum[i,j]-sum[0,i-1]=sum[0,j]-sum[i-1]

 

posted @ 2018-09-10 22:42  chan_ai_chao  阅读(98)  评论(0编辑  收藏  举报