小明很喜欢数学,有一天他在做数学作业时,要求计算出9~16的和,他马上就写出了正确答案是100。但是他并不满足于此,他在想究竟有多少种连续的正数序列的和为100(至少包括两个数)。没多久,他就得到另一组连续正数和为100的序列:18,19,20,21,22。现在把问题交给你,你能不能也很快的找出所有和为S的连续正数序列? Good Luck!
解题思路:使用滑窗法,其实实质也就是同向双指针;
注意点:当其中使用ArrayList删除元素的时候,需要注意的是,remove方法中使用的是object时,删除是元素;使用int类型的索引时,删除的是该位置上的值;
java
import java.util.ArrayList;
public class Solution {
public ArrayList<ArrayList<Integer> > FindContinuousSequence(int sum) {
ArrayList<ArrayList<Integer>> result = new ArrayList<>();
if (sum < 3) {
return result;
}
int p1 = 1;
int p2 = 2;
ArrayList<Integer> path = new ArrayList<>();
int total = 3;
path.add(p1);
path.add(p2);
while (p1 <= (sum + 1) / 2 && p2 < sum) {
if (total < sum) {
path.add(++p2);
total += p2;
} else if (total > sum) {
path.remove(new Integer(p1));
total -= p1;
p1++;
} else {
result.add(new ArrayList<Integer>(path));
path.add(++p2);
total += (p2);
}
}
return result;
}
}