-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathContinuousPositiveSequenceSumEqualTos.java
More file actions
82 lines (57 loc) · 1.59 KB
/
ContinuousPositiveSequenceSumEqualTos.java
File metadata and controls
82 lines (57 loc) · 1.59 KB
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
package swordPointOffer;
import java.util.ArrayList;
import java.util.List;
/**
* @Author: Wenhang Chen
* @Description:输入一个正整数 target ,输出所有和为 target 的连续正整数序列(至少含有两个数)。
* <p>
* 序列内的数字由小到大排列,不同序列按照首个数字从小到大排列。
* <p>
*
* <p>
* 示例 1:
* <p>
* 输入:target = 9
* 输出:[[2,3,4],[4,5]]
* 示例 2:
* <p>
* 输入:target = 15
* 输出:[[1,2,3,4,5],[4,5,6],[7,8]]
*
* <p>
* 限制:
* <p>
* 1 <= target <= 10^5
* @Date: Created in 9:14 4/11/2020
* @Modified by:
*/
public class ContinuousPositiveSequenceSumEqualTos {
public int[][] findContinuousSequence(int target) {
int i = 1; // 滑动窗口的左边界
int j = 1; // 滑动窗口的右边界
int sum = 0; // 滑动窗口中数字的和
List<int[]> res = new ArrayList<>();
while (i <= target / 2) {
if (sum < target) {
// 右边界向右移动
sum += j;
j++;
} else if (sum > target) {
// 左边界向右移动
sum -= i;
i++;
} else {
// 记录结果
int[] arr = new int[j - i];
for (int k = i; k < j; k++) {
arr[k - i] = k;
}
res.add(arr);
// 左边界向右移动
sum -= i;
i++;
}
}
return res.toArray(new int[res.size()][]);
}
}