303. Range Sum Query - Immutable

 1 static int wing=[]()
 2 {
 3     std::ios::sync_with_stdio(false);
 4     cin.tie(NULL);
 5     return 0;
 6 }();
 7 
 8 class NumArray {
 9 
10 public:
11     NumArray(vector<int> nums) 
12     {
13         int sz=nums.size();
14         cur.resize(sz+1);
15         cur[0]=0;
16         for(int i=1;i<=sz;i++)
17             cur[i]=cur[i-1]+nums[i-1];
18     }
19     
20     int sumRange(int i, int j) 
21     {
22         return cur[j+1]-cur[i];
23     }
24 
25 private:
26     vector<int> cur;
27 };
28 
29 /**
30  * Your NumArray object will be instantiated and called as such:
31  * NumArray obj = new NumArray(nums);
32  * int param_1 = obj.sumRange(i,j);
33  */

输入一个数组,再输入两个数 i 和 j ,疯狂调用求下标 i 和 j 之间元素的和

此时由于会调用多次子数组的和,所以,在读入原数组时,用一个容器作为辅助,容器第 i 个元素存放数组中前 i 个元素的和

这样一来,构建完容器之后,求子数组的和,只需要O(1)时间

猜你喜欢

转载自www.cnblogs.com/zhuangbijingdeboke/p/9089756.html