题目链接
题目描述
输出所有和为 S 的连续正数序列。
例如和为 100 的连续序列有:
[9, 10, 11, 12, 13, 14, 15, 16]
[18, 19, 20, 21, 22]。
解题思路
双指针法,小了就h++,大了就l++,相等后添加进res,然后h++
import java.util.ArrayList;
public class Solution {
public ArrayList<ArrayList<Integer> > FindContinuousSequence(int sum) {
ArrayList<ArrayList<Integer>> res = new ArrayList<>();
int l = 1, h = 2, cur = l+h;
while (h < sum) {
if (cur < sum) cur = cur + (++h);
else if (cur > sum) cur = cur - (l++);
else {
ArrayList<Integer> lst = new ArrayList<>();
for (int i=l;i<=h;i++)
lst.add(i);
res.add(lst);
cur = cur + (++h);
}
}
return res;
}
}