和为S的连续正数序列
程序员文章站
2022-07-15 23:38:58
...
import java.util.ArrayList;
public class Solution {
//双指针思路
public ArrayList<ArrayList<Integer> > FindContinuousSequence(int sum) {
ArrayList<ArrayList<Integer> >arrayList =new ArrayList<>();
if(sum<3){
return arrayList;
}
int pHigh=2,pLow=1;
while(pHigh>pLow)
{
int cur=(pHigh+pLow)*(pHigh-pLow+1)/2;
if(cur<sum)
pHigh++;
if(cur==sum){
ArrayList<Integer>arr=new ArrayList<Integer>();
for(int i=pLow;i<=pHigh;i++){
arr.add(i);
}
arrayList.add(arr);
pLow++;
}
if(cur>sum)
pLow++;
}
return arrayList;
}
public static void main(String[]args){
//System.out.println("Hello");
int sum=100;
Solution s=new Solution();
ArrayList<ArrayList<Integer>>arr=s.FindContinuousSequence(sum);
for(ArrayList<Integer>arr2:arr)
{
for(int i:arr2)
{
System.out.print(i+" ");
}
System.out.println();
}
}
}