【剑指offer】 和为s的连续正数序列,C++实现
2024-08-31 03:07:18
原创博文,转载请注明出处!
# 题目
# 思路
设置两个辅助变量small和big,small表示序列的最小值,big表示序列的最大值。如果sum(small ~ big) > s,则增大small的值。如果sum(small ~ big) < s ,则增大big的值。因为序列要求至少两个数字,所以small增加到(s+1)/2为止。
# 代码
#include <iostream>
#include <vector>
using namespace std; class Solution {
public:
vector<vector<int> > FindContinuousSequence(int sum) { // 结果
vector<vector<int> > res; // 特殊输入
if(sum<3)
return res; // 辅助变量
int small = 1;
int big = 2;
int middle = (sum+1)>>1; while(small < middle)
{
// count
int count =0;
for(int i = small;i<=big;++i)
count +=i; //
if(count == sum)
{
// 存储结果
vector<int> temp;
for(int i = small ;i <= big;++i)
{
cout<<i<<endl;
temp.push_back(i);
} res.push_back(temp); ++small;
++big;
} if(count<sum)
++big;
else
++small;
} return res;
}
};
int main()
{
int sum = 100;
Solution solution;
solution.FindContinuousSequence(sum);
return 0;
}
最新文章
- vector删除元素浅析
- jdbc-批量插入、批量删除、批量更新
- C++11 lambda的理解
- 用手机访问本地环境的利器ngrok
- GO语言练习:for基本用法
- Mirco2440核心板设计思考
- backboneJs 导图
- 全文索引--自定义chinese_lexer词典
- mysql之 binlog维护详细解析(开启、binlog相关参数作用、mysqlbinlog解读、binlog删除)
- MySQL show 语句
- Python初识2
- 初识SQL Server2017 图数据库(一)
- SpringMVC实现JSON与前台交互
- LeetCode &; Q167-Two Sum II - Input array is sorted-Easy
- 浅谈Log4net在项目中如何记录日志
- C++ Primer 有感(命名空间)
- Android 问题列表
- 用Photoshop扭曲滤镜工具打造旋转的光束效果
- [ASP.NET]static变量和viewstate的使用方法
- C/C++ 之输入输出
热门文章
- 一键安装 zabbix 2.0 版本 脚本
- Spring中Bean生命周期
- validateJarFile jar not loaded. See Servlet Spec 2.3, section 9.7.2. Offending class: javax/servlet/Servlet.class
- 读书笔记: Microsot .NET企业级应用架构设计
- JDBC 插入大批量数据
- linux du命令的疑惑
- Java输出double类型中的最小正数和最大正数
- torch 深度学习(5)
- Windows音频SDK的发展历程
- python 黑客书籍 ——扫描+暴力破解