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;
    }
};
发布了47 篇原创文章 · 获赞 28 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/qq_41122796/article/details/104707335