题目
自己解
源代码
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47class 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; } };
执行结果
还行,主要是用等差数列预处理了
优秀解
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17class 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; } };
最后
以上就是俭朴洋葱最近收集整理的关于leetcode刷题3——面试题57 - II. 和为s的连续正数序列题目自己解优秀解的全部内容,更多相关leetcode刷题3——面试题57内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复