LeetCode 303. Range Sum Query - Immutable
2016-02-02 10:26
483 查看
题目:
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.
// Your NumArray object will be instantiated and called as such:
// NumArray numArray(nums);
// numArray.sumRange(0, 1);
// numArray.sumRange(1, 2);
思路:
自底向上得到所有sumRange(0, i)的解,保存在public成员solution中; Θ(n)
sumRange(i, j) = sumRange(0, j) - sumRange(0, i - 1);
代码:C++
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.
// Your NumArray object will be instantiated and called as such:
// NumArray numArray(nums);
// numArray.sumRange(0, 1);
// numArray.sumRange(1, 2);
思路:
自底向上得到所有sumRange(0, i)的解,保存在public成员solution中; Θ(n)
sumRange(i, j) = sumRange(0, j) - sumRange(0, i - 1);
代码:C++
class NumArray { public: NumArray(vector<int> &nums) { num = nums; if (num.size() > 0) { solution.push_back(num[0]); for (int i = 1; i <= num.size() - 1; i++) { int index = solution[i - 1] + num[i]; solution.push_back(index); } } } int sumRange(int i, int j) { if (i < 0 || j >= num.size()) return 0; if (i == 0) return solution[j]; else return solution[j] - solution[i - 1]; } vector<int> solution; private: vector<int> num; };
相关文章推荐
- iOS:SVN出错 Description : The working copy is locked due to a previous error
- 【设计和开发一套简单自动化UI框架】
- iOS程序猿之UIBezierPath类属性和方法(画图路径)
- Core Bluetooth 使用教程
- IBM的云平台Bluemix使用初体验-创建第一个容器
- UE4编译配置
- UI_UISegmentedControl 控件
- 解决warning: incompatible implicit declaration of built-in function 'malloc'
- 能说easyui的性能太烂了吗?
- CodeForces 618B Guess the Permutation
- 2016太原UI设计师郭文军告你UI设计企业流程
- C# ClickOnce不支持请求执行级别"requireAdministrator"
- duilib之源码分析
- MSP430应用技巧3:MSP-FET430UIF V3驱动程序的安装
- 2.1 UIAlertView,UIActionSheet,UIDatePicker,UIPickerView使用的简单总结
- pentest - masscan-web-ui
- 从头学Qt Quick(3)-- 用QML写一个简单的颜色选择器
- Hadoop:The Definitive Guide 4th Edition
- 如何提升用户体验?绝不单单是UI那点事
- Action中获取request、response、session