303. Range Sum Query - Immutable
#week6
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:
- You may assume that the array does not change.
- There are many calls to sumRange function.
分析:
动态规划类型
状态转移方程:f[i] = f[i-1] + nums[i];
代码:
超时版本:
1 class NumArray { 2 public: 3 int** f; 4 NumArray(vector<int> nums) { 5 int len = nums.size(); 6 if (len > 0) { 7 f = new int* [len]; 8 for (int i = 0; i < len; i++) f[i] = new int[len]; 9 f[0][0] = nums[0]; 10 for (int i = 0; i < len; i++) 11 for (int j = i; j < len; j++) { 12 if (i == j) f[i][j] = nums[i]; 13 else { 14 f[i][j] = f[i][j-1] + nums[j]; 15 } 16 } 17 } else { 18 f = new int*[1]; 19 f[0] = new int[1]; 20 f[0][0] = 0; 21 } 22 } 23 24 int sumRange(int i, int j) { 25 return f[i][j]; 26 } 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 */
修改为一维,不超时:
1 class NumArray { 2 public: 3 int* f; 4 NumArray(vector<int> nums) { 5 int len = nums.size(); 6 if (len > 0) { 7 f = new int [len]; 8 f[0] = nums[0]; 9 for (int i = 1; i < len; i++) 10 f[i] = f[i-1] + nums[i]; 11 } else { 12 f = new int[1]; 13 f[0] = 0; 14 } 15 } 16 17 int sumRange(int i, int j) { 18 return f[j] - f[i-1]; 19 } 20 }; 21 22 /** 23 * Your NumArray object will be instantiated and called as such: 24 * NumArray obj = new NumArray(nums); 25 * int param_1 = obj.sumRange(i,j); 26 */