leetcode刷題3——面試題57 - II. 和爲s的連續正數序列

題目

自己解

源代碼


class Solution {
public:
	vector<vector<int>> findContinuousSequence(int target) {
		int count = 2;//每次由count個連續整數之和得到答案
		int min = target;//展開後連續數的最小值
		//int min = (target / count)-count;
		int temp;//基準數
        //int flag;
		vector<vector<int>> ans;
		while (min > 0)//首項最小項<=0的時候退出
		{			
            //flag = 0;
			temp = target / count;
			int n1 = count - 1 - count / 2;//count最小爲2,n1最小爲0,n2最小爲1
			int n2 = count / 2;//n1,n2是temp左右出現的數字,count爲偶數情況,n2=n1+1,count爲奇數情況,n2=n1;
			int test1 = (((temp - n1)+(temp + n2))*count) / 2;//n1個前連續數,temp,n2個後連續數,該序列和爲等差數列,test1爲檢測數1
			int test2 = (((temp - n2) + (temp + n1))*count) / 2;//n2個前連續數,temp,n1個後連續數,該序列和爲等差數列,test2爲檢測數2			
			
			min = (temp - n1) < (temp - n2) ? temp - n1 : temp - n2;//min等於首項中的最小值
            //min = (target / count)-count;

			if (test1 == target&&(temp - n1)>0)//防止0,1,2,3,4,5=15被錄入
			{
				vector<int> in;
				for (int i = 0; i < count; i++)//把count個連續整數輸入
					in.push_back(temp - n1 + i);//檢測1的首項逐漸+1,送入
				ans.push_back(in);
                //flag = 1;
			}
			else if (test2 == target&&test2!=test1&&(temp - n2)>0)
			{
				vector<int> in;
				for (int i = 0; i < count; i++)//把count個連續整數輸入
					in.push_back(temp - n2 + i);//檢測2的首項逐漸+1,送入
				ans.push_back(in);
                //flag = 1;
			}
			count++;//連續數數量++
			
		}
		//答案要求順序,則ans的行逆序,使用逆序迭代器
		vector<vector<int>> ans0(ans.rbegin(), ans.rend());
		return ans0;

	}
};

執行結果

還行,主要是用等差數列預處理了

優秀解

class Solution {
public:
    vector<vector<int>> findContinuousSequence(int target) {
        vector<vector<int>> res;
        int i = 1; 
        while(target > 0){
            target -= i++;
            if(target > 0 && target % i == 0){
                vector<int> tmp;
                for(int j = 0; j < i; j++) tmp.push_back(target / i + j);
                res.push_back(tmp);
            }
        }
        reverse(res.begin(), res.end());
        return res;
    }
};

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章