先给出题目:
输入一个正整数 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
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/he-wei-sde-lian-xu-zheng-shu-xu-lie-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路:首先想到的就是暴力去算,不过我没去尝试。这里我尝试用数学的方法去解题,由于考虑问题不够全面,试了几次才通过。
考虑到:
1.奇数必然可以由两个连续的数相加,而偶数可能存在无解的情况
2.由连续整数序列的特性,可以得出target必然能够由两个数相乘得到(排除第一条的情况)
具体代码如下:
复制代码
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
54class Solution { public int[][] findContinuousSequence(int target) { if (target < 3) { return new int[0][]; } double temp = (Math.sqrt(2 * target)); int n = (int) temp < temp ? (int) temp : (int) temp - 1; List<Integer> list = new LinkedList<Integer>(); for (int i = 3; i <= target / 2; i += 2) { if (target % i == 0) { if (i <= n) { list.add(i); } else { list.add((target / i) * 2); } list.sort(new Comparator<Integer>() { public int compare(Integer o1, Integer o2) { Integer i1 = o1; Integer i2 = o2; return i2.compareTo(i1); } }); } } int[][] rs = new int[target % 2 == 1 ? list.size() + 1 : list.size()][]; int col = 0; while (!list.isEmpty()) { int nums = list.remove(0); int[] row = new int[nums]; if (nums % 2 == 1) { int mid = target / nums; for (int i = 0; i < nums; i++) { row[i] = mid - nums / 2 + i; } } else { int cup = target / (nums / 2); for (int i = 0; i < nums; i++) { row[i] = cup / 2 - nums / 2 + i + 1; } } rs[col] = row; col += 1; } if (target % 2 == 1) { int[] tmrs = new int[2]; tmrs[0] = target / 2; tmrs[1] = target - tmrs[0]; rs[col] = tmrs; } return rs; } }
代码不够优雅,但总算能解决问题。
最后
以上就是谦让小懒虫最近收集整理的关于leetcode 面试题57 - II.和为s的连续正数序列的全部内容,更多相关leetcode内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复