输入一个正整数 target ,输出所有和为 target 的连续正整数序列(至少含有两个数)。
序列内的数字由小到大排列,不同序列按照首个数字从小到大排列。
示例 1:
输入:target = 9
输出:[[2,3,4],[4,5]]
示例 2:
输入:target = 15
输出:[[1,2,3,4,5],[4,5,6],[7,8]]
限制:
1 <= target <= 10^5
滑动窗口:
注意至少两个数,所以序列最左边最大为(target+1)/2,窗口范围和表示为cursum
如果cursum 小于 target , 序列右边加一个数,end++, cursum+=end
如果cursum 大于 target , 序列左边减一个数,cursum-=start,start+1
复制代码
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65#include <iostream> #include <vector> using namespace std; class Solution { public: vector<vector<int>> findContinuousSequence(int target) { if (target < 3) { return res; } int start = 1; int end = 2; int middle = (target + 1) / 2; int cursum = start + end; while (start<middle) { if (cursum == target) { getson(start, end); } while (cursum >target && start < middle) { cursum -= start; start++; if (cursum == target) { getson(start, end); } } end++; cursum += end; } return res; } void getson(int start, int end) { vec.clear(); for (int i = start; i <= end; i++) { vec.push_back(i); } res.push_back(vec); } private: vector<int> vec; vector<vector<int>> res; }; int main() { Solution* ps = new Solution(); vector<vector<int>> res = ps->findContinuousSequence(9); for (int i = 0; i < res.size(); i++) { for (int j = 0; j < res[i].size(); j++) { cout << res[i][j]; } cout << endl; } return 0; }
最后
以上就是狂野猎豹最近收集整理的关于LeetCode-面试题57 - II. 和为s的连续正数序列的全部内容,更多相关LeetCode-面试题57内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复