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:
TIME LIMITED EXCEEDED VERSION
1 class NumArray { 2 private: 3 vector<int> arr; 4 public: 5 NumArray(vector<int> &nums) { 6 arr.clear(); 7 for(int i = 0; i < nums.size(); i++) 8 arr.push_back(nums[i]); 9 } 10 11 int sumRange(int i, int j) { 12 i = i < 0 ? 0 : i; 13 j = j >= arr.size() ? arr.size() - 1 : j; 14 15 int sum = 0; 16 for(int k = i; k <= j; k++) 17 sum += arr[k]; 18 return sum; 19 } 20 }; 21 22 23 // Your NumArray object will be instantiated and called as such: 24 // NumArray numArray(nums); 25 // numArray.sumRange(0, 1); 26 // numArray.sumRange(1, 2);
Runtime: 588ms
1 class NumArray { 2 public: 3 NumArray(vector<int> &nums) { 4 arr.push_back(0); 5 for(int i = 0; i < nums.size(); i++) 6 arr.push_back(arr[i] + nums[i]); 7 } 8 9 int sumRange(int i, int j) { 10 return arr[j + 1] - arr[i]; 11 } 12 private: 13 vector<int> arr; 14 }; 15 16 17 // Your NumArray object will be instantiated and called as such: 18 // NumArray numArray(nums); 19 // numArray.sumRange(0, 1); 20 // numArray.sumRange(1, 2);
原文:http://www.cnblogs.com/amazingzoe/p/4954937.html