剑指offer---和为S的连续正数序列
题目:和为S的连续正数序列
要求:输入一个正数S,返回所有和为S的正数序列,见下例;
例如:
输入:
- S=15
输出:
- {1, 2, 3, 4, 5}
- {4, 5, 6}
- {7, 8}
class Solution { public: vector<vector<int> > FindContinuousSequence(int sum) { } };
解题代码:
class Solution { public: vector<vector<int> > FindContinuousSequence(int sum) { // 边界处理 vector<vector<int> > res; if(sum < 3) return res; // int mid = (sum + 1)/2; int low = 1; int high = 2; while(low < mid){ if(mysum(low, high) < sum) high++; else if(mysum(low, high) > sum) low++; else{ res.push_back(printRes(low, high)); high++; } } return res; } private: // 计算从start到end的和 int mysum(int start, int end){ int sum = 0; while(start <= end){ sum += start; start++; } return sum; } // 将start到end之间的数字保存到subRes vector<int> printRes(int start, int end){ vector<int> subRes; while(start <= end){ subRes.push_back(start); start++; } return subRes; } };
更新一下,发现上述代码(运行时间:4ms占用内存:600k)计算求和的时候出现了重复计算的问题,没有很好的利用上次计算的结果,改进版本如下:
class SolutionOpt { public: vector<vector<int> > FindContinuousSequence(int sum) { // 边界处理 vector<vector<int> > res; if(sum < 3) return res; // int mid = (sum + 1)/2; int low = 1; int high = 2; int curSum = low + high; while(low < mid){ if(curSum == sum) res.push_back(printSubRes(low, high)); while(curSum > sum && low < high){ curSum -= low; low++; if(curSum == sum) res.push_back(printSubRes(low, high)); } high++; curSum += high; } return res; } private: // 将start到end之间的数字保存到subRes vector<int> printSubRes(int start, int end){ vector<int> subRes; while(start <= end){ subRes.push_back(start); start++; } return subRes; } };
改进版运行时间:3ms,占用内存:472k