Range Sum Query - Immutable
2015-11-12 12:03
330 查看
题目链接
原题
思路
code
原题
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.
思路
动态规划.
code
class NumArray { public: NumArray(vector<int> &nums) { if(!nums_.empty()) { nums_.clear(); } if(!sums_.empty()) { sums_.clear(); } if(nums.empty()) return; for(int i = 0; i < nums.size(); i++) { nums_.push_back(nums[i]); // if(i == 0) { // sums_.push_back(nums_[i]); // } else { // sums_.push_back(nums_[i] + sums_[i - 1]); // } } sums_.push_back(nums_[0]); for(int i = 1; i < nums.size(); i++) { sums_.push_back(nums_[i] + sums_[i - 1]); } } int sumRange(int i, int j) { int sum = 0; if(j < i) std::swap(i, j); // for(int idx = i; idx <= j; idx++) { // sum += nums_[idx]; // } return sums_[j] - sums_[i] + nums_[i]; return sum; } private: vector<int> nums_; vector<int> sums_; }; // Your NumArray object will be instantiated and called as such: // NumArray numArray(nums); // numArray.sumRange(0, 1); // numArray.sumRange(1, 2);
相关文章推荐
- Range Sum Query 2D - Immutable
- ios CoreBluetooth 警告 is being dealloc'ed while pending connection
- UINavigation设置背景颜色后 界面适配的问题
- UItableView 的使用总结
- requestWindowFeature()使用简介
- StringBuilde的用法
- UITableViewStylePlain实现分组效果
- UITextField 限制输入字符
- LeetCode Longest Increasing Subsequence
- 让UIView转起来
- Android.mk 小细节(LOCAL_CFLAGS 、BUILD_PREBUILT)
- UIImageView 小幅度震动动画
- uialert IOS8
- 我的BluetoothChat示例源码阅读笔记
- Ligerui表格基本操作(三)
- Solve Hibernate Lazy-Init issue with hibernate.enable_lazy_load_no_trans
- Repeated DNA Sequences
- LeetCode---Implement Queue using Stacks
- 设置UIButton的title 闪动效果的解决办法
- paint.setAntiAlias(true);