Skip to content

Commit 69fb7b0

Browse files
committed
feat: add python and java solutions to lcof problem
添加《剑指 Offer》题解:面试题57 - II. 和为s的连续正数序列
1 parent e40ab3d commit 69fb7b0

File tree

3 files changed

+120
-0
lines changed

3 files changed

+120
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
# [面试题57 - II. 和为s的连续正数序列](https://leetcode-cn.com/problems/he-wei-sde-lian-xu-zheng-shu-xu-lie-lcof/)
2+
3+
## 题目描述
4+
输入一个正整数 `target` ,输出所有和为 `target` 的连续正整数序列(至少含有两个数)。
5+
6+
序列内的数字由小到大排列,不同序列按照首个数字从小到大排列。
7+
8+
**示例 1:**
9+
10+
```
11+
输入:target = 9
12+
输出:[[2,3,4],[4,5]]
13+
```
14+
15+
**示例 2:**
16+
17+
```
18+
输入:target = 15
19+
输出:[[1,2,3,4,5],[4,5,6],[7,8]]
20+
```
21+
22+
**限制:**
23+
24+
- `1 <= target <= 10^5`
25+
26+
## 解法
27+
双指针:`p = 1``q = 2`
28+
29+
### Python3
30+
```python
31+
class Solution:
32+
def findContinuousSequence(self, target: int) -> List[List[int]]:
33+
res = []
34+
p, q = 1, 2
35+
while p < q:
36+
s = (p + q) * (q - p + 1) >> 1
37+
if s == target:
38+
res.append([i for i in range(p, q + 1)])
39+
p += 1
40+
elif s < target:
41+
q += 1
42+
else:
43+
p += 1
44+
return res
45+
```
46+
47+
### Java
48+
```java
49+
class Solution {
50+
public int[][] findContinuousSequence(int target) {
51+
List<int[]> list = new ArrayList<>();
52+
int p = 1, q = 2;
53+
while (p < q) {
54+
int s = (p + q) * (q - p + 1) >> 1;
55+
if (s == target) {
56+
int[] t = new int[q - p + 1];
57+
for (int i = 0; i < t.length; ++i) {
58+
t[i] = p + i;
59+
}
60+
list.add(t);
61+
++p;
62+
} else if (s < target) {
63+
++q;
64+
} else {
65+
++p;
66+
}
67+
}
68+
int[][] res = new int[list.size()][];
69+
for (int i = 0; i < res.length; ++i) {
70+
res[i] = list.get(i);
71+
}
72+
return res;
73+
}
74+
}
75+
```
76+
77+
### ...
78+
```
79+
80+
```
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
class Solution {
2+
public int[][] findContinuousSequence(int target) {
3+
List<int[]> list = new ArrayList<>();
4+
int p = 1, q = 2;
5+
while (p < q) {
6+
int s = (p + q) * (q - p + 1) >> 1;
7+
if (s == target) {
8+
int[] t = new int[q - p + 1];
9+
for (int i = 0; i < t.length; ++i) {
10+
t[i] = p + i;
11+
}
12+
list.add(t);
13+
++p;
14+
} else if (s < target) {
15+
++q;
16+
} else {
17+
++p;
18+
}
19+
}
20+
int[][] res = new int[list.size()][];
21+
for (int i = 0; i < res.length; ++i) {
22+
res[i] = list.get(i);
23+
}
24+
return res;
25+
}
26+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
class Solution:
2+
def findContinuousSequence(self, target: int) -> List[List[int]]:
3+
res = []
4+
p, q = 1, 2
5+
while p < q:
6+
s = (p + q) * (q - p + 1) >> 1
7+
if s == target:
8+
res.append([i for i in range(p, q + 1)])
9+
p += 1
10+
elif s < target:
11+
q += 1
12+
else:
13+
p += 1
14+
return res

0 commit comments

Comments
 (0)