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」!

最新文章

  1. Java学习笔记(二二)——Java HashMap
  2. python 运行时报错误SyntaxError: Non-ASCII character &#39;\xe5&#39; in file 1.py on line 2
  3. POJ 1556 The Doors --几何,最短路
  4. 禁止ViewState的3种解决方法
  5. IAR:Error [Li005]:no definition for&quot;***&quot; 问题之连接
  6. unity 导出 android安装包配置方案
  7. c#中总是提示“在代码运行时或者在禁用“只要一个进程中断,就中断所有进程”选项时,不允许进行更改。
  8. 使用astyle格式化代码
  9. update语句的执行步骤及commit语句的执行顺序
  10. SQLSERVER2014的内存优化表
  11. cocos2d-x 3.0 cocos run Couldn&#39;t find the gcc toolchain.
  12. chm提取
  13. PHP配置文件php.ini详解
  14. WinAFL
  15. grp/从Zipkin到Jaeger,Uber的分布式追踪之道tchannel--zipkin with mysql in docker-compose
  16. curl发送post请求,统计响应时间
  17. centos7 安装 jdk1.8
  18. 代理神器allproxy
  19. Daily Scrum 11.7
  20. xp局域网共享设置

热门文章

  1. ActionBar自己定义改动无效解决方法
  2. DG不同步,MRP0进程打不开
  3. DateFormat多线程使用问题
  4. to meet you
  5. http 协议状态码
  6. 用file标签实现多图文件上传预览
  7. 给网页标签页添加logo
  8. scala爬取指定地点的所有列车班次
  9. Flume(3)-安装部署
  10. 大数据:Windows下配置flink的Stream