题目描述:
输入一个正整数 target ,输出所有和为 target 的连续正整数序列(至少含有两个数)。
序列内的数字由小到大排列,不同序列按照首个数字从小到大排列。
示例 1:
输入:target = 9
输出:[[2,3,4],[4,5]]
示例 2:
输入:target = 15
输出:[[1,2,3,4,5],[4,5,6],[7,8]]
限制:
复制代码
1
21 <= target <= 10^5
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/he-wei-sde-lian-xu-zheng-shu-xu-lie-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
解法:
复制代码
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
34class Solution { public int[][] findContinuousSequence(int target) { List<int[]> res = new ArrayList<>(); int l = 1; int r = 2; int border = target / 2 + 1; while (r <= border && l < border) { if (l == r) { r++; continue; } int sum = (l + r) * (r - l + 1) / 2; if (sum == target) { int[] temp = add(l, r); res.add(temp); l++; } else if (sum < target) { r++; } else if (sum > target) { l++; } } return res.toArray(new int[0][]); } private int[] add(int start, int end) { int[] arr = new int[end - start + 1]; for (int i = start, j = 0; i <= end; i++, j++) { arr[j] = i; } return arr; } }
最后
以上就是俊秀白昼最近收集整理的关于面试题57 - II. 和为s的连续正数序列(简单题)的全部内容,更多相关面试题57内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复