[leetcode 303] Range Sum Query - Immutable
2015-12-08 22:29
441 查看
Question:
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
分析:
直接创建一个vector<int>成员变量,变量长度与NUMS变量长度+1相等
vector<int>成员变量中第i个元素表示在nums中第i个元素以前的数据和;
所以sumRange(i,j)= vector<int> [j+1] - vector<int>[i];
代码:
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
分析:
直接创建一个vector<int>成员变量,变量长度与NUMS变量长度+1相等
vector<int>成员变量中第i个元素表示在nums中第i个元素以前的数据和;
所以sumRange(i,j)= vector<int> [j+1] - vector<int>[i];
代码:
<span style="font-size:14px;">class NumArray { private: vector<int> sumArray= {0}; public: NumArray(vector<int> &nums) { int summ = 0; for (int n : nums) { summ += n; sumArray.push_back(summ); } } int sumRange(int i, int j) { return sumArray[j+1] - sumArray[i]; } }; // Your NumArray object will be instantiated and called as such: // NumArray numArray(nums); // numArray.sumRange(0, 1); // numArray.sumRange(1, 2);</span>
相关文章推荐
- iOS技术面试05:UI控件
- @Responsebody与@RequestBody
- ERROR BUILDING VIM on Ubuntu--Solution
- UIScrollView和UIPageControl的分页 && NSTimer【图片轮播器】
- 如何在UICollectionView reloadData后找到的某个cell
- 解决iOS UITextView没有placeholder
- 【Codeforces Round 276 (Div 2)D】【数论 正难则反 枚举倍数 二分 O(nlogn)】Maximum Value n个数大数mod小数找最大余数
- UIView的bounds到底是干嘛的
- Query.extend() 函数详解-转载
- 旧Mj下拉刷新 An instance 0xca90200 of class UITableView was deallocated while key value observers were s
- UVALive-2531 The K-League (最大流建模+枚举)
- lucene的多种搜索2-SpanQuery
- UITableViewCell contentView layoutSubviews 死循环
- js实现卡片式项目管理界面UI设计效果
- lucene-SpanQuery跨度查询基础
- Lucene中的 Query对象
- lucene-SpanFirstQuery 和SpanNearQuery 跨度查询
- lucene-SpanNotQuery和SpanOrQuery交迭与全局跨度
- ios学习笔记(七)关于NSUInteger
- ios学习笔记(七)关于NSUInteger