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