-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNo57NSum.java
More file actions
39 lines (35 loc) · 931 Bytes
/
No57NSum.java
File metadata and controls
39 lines (35 loc) · 931 Bytes
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
package com.wzx.sword;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.IntStream;
/**
* @see <a href="https://leetcode-cn.com/problems/he-wei-sde-lian-xu-zheng-shu-xu-lie-lcof/">https://leetcode-cn.com/problems/he-wei-sde-lian-xu-zheng-shu-xu-lie-lcof/</a>
* @author wzx
*/
public class No57NSum {
/**
* 滑动窗口
*
* time: O(n)
* space: O(1)
*/
public int[][] findContinuousSequence(int target) {
List<int[]> res = new ArrayList<>();
int left = 1, right = 2;
while (left < right) {
// 求和公式
int sum = (left + right) * (right - left + 1) / 2;
if (sum > target) {
// 窗口右移
left++;
} else if (sum < target) {
// 增大窗口
right++;
} else {
res.add(IntStream.rangeClosed(left, right).toArray());
left++;
}
}
return res.toArray(new int[res.size()][]);
}
}