剑指offer——和为S的连续正数序列

题目链接:小明很喜欢数学,有一天他在做数学作业时,要求计算出9~16的和,他马上就写出了正确答案是100。但是他并不满足于此,他在想究竟有多少种连续的正数序列的和为100(至少包括两个数)。没多久,他就得到另一组连续正数和为100的序列:18,19,20,21,22。现在把问题交给你,你能不能也很快的找出所有和为S的连续正数序列? Good Luck!

解题思路:

双指针滑动窗口。

 1 import java.util.ArrayList;
 2 public class Solution {
 3     public ArrayList<ArrayList<Integer> > FindContinuousSequence(int sum) {
 4        
 5         ArrayList <ArrayList<Integer> > result = new ArrayList<>();
 6         int plow=1;
 7         int phigh=2;
 8         while(plow<phigh)
 9         {
10             int cur=(phigh+plow)*(phigh-plow+1)/2;
11             
12             if(cur == sum)
13             {
14                 ArrayList<Integer> list = new ArrayList<>();
15                 for(int i=plow;i<=phigh;i++)
16                 {
17                     list.add(i);
18                 }
19                 result.add(list);
20                 plow++;
21             }
22             else if(cur<sum)
23             {
24                 phigh++;
25             }
26             else
27             {
28                 plow++;
29             }
30         }
31         return result;
32     }
33 }
原文地址:https://www.cnblogs.com/wangyufeiaichiyu/p/10872354.html