剑指41 - 和为S的连续正数序列
小明很喜欢数学,有一天他在做数学作业时,要求计算出9~16的和,他马上就写出了正确答案是100。
但是他并不满足于此,他在想究竟有多少种连续的正数序列的和为100(至少包括两个数)。
没多久,他就得到另一组连续正数和为100的序列:18,19,20,21,22。现在把问题交给你,你能不能也很快的找出所有和为S的连续正数序列? Good Luck!
输出描述:
输出所有和为S的连续正数序列。序列内按照从小至大的顺序,序列间按照开始数字从小到大的顺序
示例1
输入
9
输出
[[2,3,4],[4,5]]
解法一:
import java.util.*;
public class Solution {
public ArrayList<ArrayList<Integer> > FindContinuousSequence(int sum) {
ArrayList<ArrayList<Integer> > result = new ArrayList<ArrayList<Integer> >();
if(sum <=0) return result;
for(int i=sum-1; i>0; i--) {
int remain = sum;
int cnt = 0;
while(remain > 0) {
remain = remain - i + cnt;
cnt++;
}
if(remain < 0) {
continue;
} else {
ArrayList<Integer> temp = new ArrayList<Integer>();
for(int j=0; j<cnt; j++) {
temp.add(i-j);
}
Collections.sort(temp);// 题目要求从小到大
result.add(temp);
}
}
Collections.reverse(result); // 题目要求从小到大
return result;
}
}
解法二:双指针+窗口(推荐)
import java.util.*;
public class Solution {
public ArrayList<ArrayList<Integer> > FindContinuousSequence(int sum) {
ArrayList<ArrayList<Integer> > result = new ArrayList<ArrayList<Integer> >();
if(sum <=0) return result;
int pHi = 2, pLo = 1;
// 窗口一直右移
while(pHi > pLo) {
// 等差数列求和(头加尾)*(项数)/2
int currentSum = (pHi+pLo)* (pHi-pLo+1)/2;
if(currentSum == sum) {
ArrayList<Integer> tempList = new ArrayList<Integer>();
for(int i=pLo; i<=pHi; i++) {
tempList.add(i);
}
result.add(tempList);
pLo++; // 窗口右移,继续寻找
} else if(currentSum < sum) {
// 当前窗口和小于目标和时,扩大窗口
pHi++;
} else {
// 当前窗口和大于目标和时,缩小窗口
pLo++;
}
}
return result;
}
}