标签:psu slist add integer import find class 工作 ==
package wangChaoPA实习工作练习.com.剑指offer;
import java.util.ArrayList;
/*
* 解题思路:因为是连续的,所以利用大小数进行解答 如果从little到big的和等于sum
* 保存little到big值到list中然后,little++,big++ 如果从little到big的和小于sum big++
* 如果从little到big的大等sum little++
*/
public class 和为S的连续正整数序列
{
public ArrayList<ArrayList<Integer>> FindContinuousSequence(int sum)
{
ArrayList<ArrayList<Integer>> resList = new ArrayList<ArrayList<Integer>>();
if (sum < 3)
{
return resList;
}
int little = 1;
int big = 2;
// little最大只能为sum的一半
while (little <= sum / 2)
{
int tempSum = sumOflittleToBig(little, big);
if (tempSum == sum)
{
ArrayList<Integer> list = new ArrayList<Integer>();
for (int i = little; i <= big; i++)
{
list.add(i);
}
resList.add(list);
little++;
big++;
}
else if (tempSum < sum)
{
big++;
}
else
{
little++;
}
}
return resList;
}
private int sumOflittleToBig(int little, int big)
{
int sum = 0;
for (int i = little; i <= big; i++)
{
sum += i;
}
return sum;
}
}
标签:psu slist add integer import find class 工作 ==
原文地址:http://www.cnblogs.com/qingtianBKY/p/7203476.html