剑指offer:和为S的连续正数序列
一、题目描述
小明很喜欢数学,有一天他在做数学作业时,要求计算出9~16的和,他马上就写出了正确答案是100。但是他并不满足于此,他在想究竟有多少种连续的正数序列的和为100(至少包括两个数)。没多久,他就得到另一组连续正数和为100的序列:18,19,20,21,22。现在把问题交给你,你能不能也很快的找出所有和为S的连续正数序列? Good Luck!
输出描述:
输出所有和为S的连续正数序列。序列内按照从小至大的顺序,序列间按照开始数字从小到大的顺序
二、思路
使用滑动窗口的思想,设置两个指针plow和phigh指向窗口的两端。使用求和公式求cur(公差为1),
如果cur与目标sum相同则将窗口内的数字加入结果集,否则如果cur小于sum则窗口右指针右移,
如果cur大于sum则窗口左指针右移。
三、代码
import java.util.ArrayList;
public class Solution {
public ArrayList<ArrayList<Integer> > FindContinuousSequence(int sum) {
int plow=1,phigh=2;
ArrayList<ArrayList<Integer>> result = new ArrayList<>();
while(plow<phigh){
int cur = (plow+phigh)*(phigh-plow+1)/2;
ArrayList<Integer> list = new ArrayList<>();
if(sum==cur){
for(int i=plow;i<=phigh;i++){
list.add(i);
}
result.add(list);
plow++;
}else if(sum<cur){
plow++;
}else{
phigh++;
}
}
return result;
}
}

浙公网安备 33010602011771号