剑指 Offer——和为 S 的连续正数序列
2024-10-19 19:42:43
1. 题目
2. 解答
定义两个指针,刚开始分别指向 1 和 2,求出位于这两个指针之间的元素和。如果和大于 S,前面的指针向后移直到和不大于 S 为止;反之,如果和等于 S,则此时两个指针之间的元素序列即为一个所求的结果,后面的指针向后移动。
第一个指针的范围为 \([1, \frac{S+1}{2})\),左闭右开,可举一个奇数偶数的例子即可知。时间复杂度为 \(O(n)\)。
class Solution {
public:
vector<vector<int> > FindContinuousSequence(int sum) {
int middle = (sum + 1) / 2;
int small = 1;
int big = 2;
int target = small + big;
vector<vector<int> > result;
while (small < middle)
{
if (target > sum)
{
while (small < middle && target > sum)
{
target -= small;
small++;
}
}
else
{
if (target == sum) Add_Sequence(result, small, big);
big++;
target += big;
}
}
return result;
}
void Add_Sequence(vector<vector<int> > &result, int small, int big)
{
vector<int> temp;
for (int i = small; i <= big; i++)
temp.push_back(i);
result.push_back(temp);
}
};
获取更多精彩,请关注「seniusen」!
最新文章
- Java学习笔记(二二)——Java HashMap
- python 运行时报错误SyntaxError: Non-ASCII character &#39;\xe5&#39; in file 1.py on line 2
- POJ 1556	 The Doors --几何,最短路
- 禁止ViewState的3种解决方法
- IAR:Error [Li005]:no definition for";***"; 问题之连接
- unity 导出 android安装包配置方案
- c#中总是提示“在代码运行时或者在禁用“只要一个进程中断,就中断所有进程”选项时,不允许进行更改。
- 使用astyle格式化代码
- update语句的执行步骤及commit语句的执行顺序
- SQLSERVER2014的内存优化表
- cocos2d-x 3.0 cocos run Couldn&#39;t find the gcc toolchain.
- chm提取
- PHP配置文件php.ini详解
- WinAFL
- grp/从Zipkin到Jaeger,Uber的分布式追踪之道tchannel--zipkin with mysql in docker-compose
- curl发送post请求,统计响应时间
- centos7 安装 jdk1.8
- 代理神器allproxy
- Daily Scrum 11.7
- xp局域网共享设置