1. 程式人生 > >【劍指offer】 和為s的連續正數序列,C++實現

【劍指offer】 和為s的連續正數序列,C++實現

轉載 urn 劍指offer find small vector tps cout AD

原創博文,轉載請註明出處!

# 題目

技術分享圖片

# 思路

設置兩個輔助變量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; }

【劍指offer】 和為s的連續正數序列,C++實現