# 剑指offer之和为S的两个数字 vs 和为S的连续正数序列

## 参考代码

class Solution {
public:
vector<int> FindNumbersWithSum(vector<int> array,int sum) {
vector<int> res;
if(array.size() < 2)
return res;
int i = 0;
int j = array.size()-1;
while(i < j){
if(array[i] + array[j] == sum){
res.push_back(array[i]);
res.push_back(array[j]);
break;
}
else if(array[i] + array[j] > sum){
j--;
}
else
i++;
}
return res;
}
};

## 参考代码

class Solution {
public:
vector<vector<int> > FindContinuousSequence(int sum) {
vector<vector<int>> res;
if(sum <= 1)
return res;
int small = 1;
int big = 2;
while(small != (1 + sum) / 2){
int curSum = (small + big)*(big - small + 1) / 2;
if(curSum == sum){
vector<int> oneList;
for(int i = small;i <= big;i++)
oneList.push_back(i);
res.push_back(oneList);
small++;
big++;
}
else if(curSum < sum)
big++;
else
small++;
}
return res;
}
};

## 方法二：

b + b + 1 + b + 2 + … + b + a -1 = S
ab + a(a-1)/2 = S
a(2b + a - 1) = 2S

public class Solution {
public ArrayList<ArrayList<Integer>> FindContinuousSequence(int sum) {
ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();
for(int a = 2; a * a < 2 * sum; a ++){ //有a个连续的整数
if(2*sum % a == 0){//a是2*sum的约数
if((2*sum + a - a*a) / (2 * a) > 0 && (2*sum + a - a*a) % (2 * a) == 0){
ArrayList<Integer> al = new ArrayList<Integer>();
for(int i = (2*sum + a - a*a) / (2 * a); i < ((2*sum + a - a*a) / (2 * a) + a); i ++){
}
}
}
}
return res;
}
}

• 广告
• 抄袭
• 版权
• 政治
• 色情
• 无意义
• 其他

120