leetcode之Range Sum Query - Immutab
2016-04-06 13:38
288 查看
Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive.
Example:
Note:
You may assume that the array does not change.
There are many calls to sumRange function.
该题目的主要思想是:因为会多次调用数值计算,所以如果每次进行暴力计算的话,会浪费大量的时间,所以选择先计算出前n项的和,在求两下标直接的和时,只需要直接进行减法运算即可。在程序运行时,应该注意i==0的情况,这个地方容易造成超出内存的错误,所以我加了一个判定条件。
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.
该题目的主要思想是:因为会多次调用数值计算,所以如果每次进行暴力计算的话,会浪费大量的时间,所以选择先计算出前n项的和,在求两下标直接的和时,只需要直接进行减法运算即可。在程序运行时,应该注意i==0的情况,这个地方容易造成超出内存的错误,所以我加了一个判定条件。
class NumArray { public: vector<int> sum; NumArray(vector<int> &nums) { //计算从begin~end每个位置和 if (nums.empty()) return; else{ sum.push_back(nums[0]); for (vector<int>::size_type index = 1; index != nums.size(); ++index){ sum.push_back(nums[index] + sum[index - 1]); } } } int sumRange(int i, int j) { if (i == 0){ //cout << sum[j]; return sum[j]; } else { //cout << sum[j] - sum[i - 1] << endl; return(sum[j] - sum[i-1]); } } }; // Your NumArray object will be instantiated and called as such: // NumArray numArray(nums); // numArray.sumRange(0, 1); // numArray.sumRange(1, 2);
相关文章推荐
- Jenkins上svn: E175002: Processing REPORT request response failed问题的排查过程
- iCheck如何获得id与value
- Android MeasuerSpce using
- (CF#257)B. Jzzhu and Sequences
- Easyui-ComboTree数据填充,递归。树形节点
- 如何为UICollectionView的每一个组设置不同的颜色
- UVA_10099_The Tourist Guide_kruscal
- IPtables中SNAT和MASQUERADE的区别
- Requests库使用
- Android Call requires API level 11 (current min is 8)的解决方案
- Android MeasuerSpec的由来及使用
- NSURL 、NSURLRequest、NSURLConnection、NSURLSession、NSURLSessionDataTask
- UiAutomator viewer 在tools下启动、资源jar包在platforms下(如android22)
- UVa 540 Team Queue
- Java Map 按Key排序和按Value排序
- Ui_Spinner
- iOS监听UITextField的输入事件
- android.util.MalformedJsonException: Use JsonReader.setLenient(true) to accept malformed JSON at lin
- 【Android UI设计与开发】8.顶部标题栏(一)ActionBar 奥义·详解
- get和post、cookie和session、include和require之前的区别