题目
小明很喜欢数学,有一天他在做数学作业时,要求计算出9~16的和,他马上就写出了正确答案是100。但是他并不满足于此,他在想究竟有多少种连续的正数序列的和为100(至少包括两个数)。没多久,他就得到另一组连续正数和为100的序列:18,19,20,21,22。现在把问题交给你,你能不能也很快的找出所有和为S的连续正数序列? Good Luck!
输出描述:
输出所有和为S的连续正数序列。序列内按照从小至大的顺序,序列间按照开始数字从小到大的顺序
思路
1、穷举
2、双指针滑动窗口
实现
1、
import java.util.ArrayList;
public class Solution {
public ArrayList<ArrayList<Integer> > FindContinuousSequence(int sum) {
ArrayList<ArrayList<Integer> >result=new ArrayList<ArrayList<Integer> >();
//ArrayList<Integer> list=new ArrayList<Integer>();//穷举法也要new list将这一步放到循环中
for(int i=1;i<sum;i++){
int count=0;
int j=i;
while(count<sum){
count+=j;
j++;
}
if(count==sum){
ArrayList<Integer> list=new ArrayList<Integer>();
for(int k=i;k<j;k++){
list.add(k);
}
result.add(list);
}
}
return result;
}
}
2、
import java.util.ArrayList;
public class Solution {
public ArrayList<ArrayList<Integer> > FindContinuousSequence(int sum) {
ArrayList<ArrayList<Integer> > result=new ArrayList<ArrayList<Integer> >();
//两个起点,相当于动态窗口的两边,根据其窗口内的值的和来确定窗口的位置和大小
int plow=1,phigh=2;//连续的递增1的序列
while(plow<phigh){
//由于是连续的,差为1的一个序列,那么求和公式是(a0+an)*n/2
int count=(plow+phigh)*(phigh-plow+1)/2;
if(count==sum){
ArrayList<Integer> list=new ArrayList<Integer>();
for(int i=plow;i<=phigh;i++){
list.add(i);
}
result.add(list);
plow++;
}else if(count<sum){//值小于,窗口扩大,右指针右移
phigh++;
}else{//值大于,窗口缩小,左指针右移,当左右指针重叠,则退出
plow++;
}
}
return result;
}
}