-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathFindContinuousSequence.java
More file actions
39 lines (33 loc) · 1.07 KB
/
FindContinuousSequence.java
File metadata and controls
39 lines (33 loc) · 1.07 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
package com.company;
import org.junit.Test;
import java.util.ArrayList;
public class FindContinuousSequence {
public ArrayList<ArrayList<Integer>> FindContinuousSequence(int sum) {
ArrayList<ArrayList<Integer>> mArrayLists = new ArrayList<>();
// 高位指针和低位指针
int pLow = 1;
int pHigh = 2;
// 终止条件是pHigh等于sum
while (pHigh > pLow) {
// 当前和,使用求和公式s = (a+b) * n / 2
int curSum = (pLow + pHigh) * (pHigh - pLow + 1) >> 1;
if (curSum < sum) pHigh++;
if (curSum == sum) {
ArrayList<Integer> temp = new ArrayList<>();
for (int i = pLow; i <= pHigh; i++) {
temp.add(i);
}
mArrayLists.add(temp);
pLow++;
}
if (curSum > sum) {
pLow++;
}
}
return mArrayLists;
}
@Test
public void test() {
FindContinuousSequence(100);
}
}