leetcode range sum query
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.
刚开始看题,有些不懂,暴力破解后time exceed。很简单,聪明的人大概一会儿就想出来了。
1 class NumArray { 2 vector<int> sumArray; 3 public: 4 NumArray(vector<int> &nums) { 5 6 int temp=0; 7 for(int i=0;i<nums.size();i++){ 8 temp+=nums[i]; 9 sumArray.push_back(temp); 10 } 11 } 12 13 int sumRange(int i, int j) { 14 int result; 15 result=this->sumArray[j]-this->sumArray[i-1]; 16 return result; 17 } 18 }; 19 20 21 // Your NumArray object will be instantiated and called as such: 22 // NumArray numArray(nums); 23 // numArray.sumRange(0, 1); 24 // numArray.sumRange(1, 2);
题外话:
最近状态有些不好,我事实上是一个常常状态不好的人,我【容易受环境干扰】、【理性感性参半】、【不容易坚守自己】
因为上述的缺点,常常陷入责怪自己的状态中,却不知道如何改变,最差却一直使用的解决办法就是明天再说,也许明天就好了。呸。